LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby】Rubyコードのパフォーマンスを計測したい

Posted at

概要

Rubyのパフォーマンスを計測するためprofile.rbを使用して計測します。
実際に速度が遅くなっていないかを調べることがあったためメモとして残す。

テストコード(フィボナッチ数列)

test_fib.rb

def fibonacci(i)
  (i == 0 || i == 1) ? 1 : fibonacci(i - 1) + fibonacci(i - 2)
end
n = 20
puts "fib(%d) = %d" % [n, fibonacci(n)]

そのまま実行すると

$ ruby test_fib.rb 
fib(20) = 10946

profile.rbを使用して実行すると

$ ruby -rprofile test_fib.rb 
fib(20) = 10946
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 85.25     0.52      0.52    21891     0.02     0.38  Object#fibonacci
  6.56     0.56      0.04    10945     0.00     0.00  Fixnum#+
  4.92     0.59      0.03    39601     0.00     0.00  Fixnum#==
  3.28     0.61      0.02    21890     0.00     0.00  Fixnum#-
  0.00     0.61      0.00        1     0.00     0.00  String#%
  0.00     0.61      0.00        2     0.00     0.00  IO#write
  0.00     0.61      0.00        1     0.00     0.00  IO#puts
  0.00     0.61      0.00        1     0.00     0.00  Kernel#puts
  0.00     0.61      0.00        1     0.00     0.00  TracePoint#enable
  0.00     0.61      0.00        1     0.00     0.00  TracePoint#disable
  0.00     0.61      0.00        1     0.00     0.00  Kernel#respond_to?
  0.00     0.61      0.00        2     0.00     0.00  IO#set_encoding
  0.00     0.61      0.00        1     0.00     0.00  Module#method_added
  0.00     0.61      0.00        1     0.00   610.00  #toplevel

となり、簡単ではあるがパフォーマンスを計測できる。
各フィールドの意味は左から順に次の通り。

  • 全体時間のパーセンテージ
  • 全体時間の総和(単位は秒)
  • 正味時間の総和(秒)
  • 呼び出された回数
  • 1回の呼び出し当たりの平均正味時間(ミリ秒)
  • 1回の呼び出し当たりの平均全体時間(ミリ秒)
  • メソッド名

参考

profile.rb - Rubyリファレンスマニュアル
http://uralowl.my.coocan.jp/unix/job/UNIX/tool/ruby/profile_rb.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0