Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | RubyのBenchmark測定

概要

RubyのBenchmark測定

詳細

RubyのBenchmarkを扱う方法について。
Benchmarkモジュールでコードの実行時間を計測出来ます。

サンプルコード

require 'benchmark'
include Benchmark

LOOP_COUNT = 1000

TEST_NUMBER_LIST = (1..100).to_a
TEST_STRING_LIST = ("1".."100").to_a

def summary_number(list)
  list.inject(:+)
end

def summary_string(list)
  list.inject {|sum, cnt|sum.to_i + cnt.to_i}
end

bmbm do |test|
  test.report("summary_number:") do
    LOOP_COUNT.times {|x|summary_number(TEST_NUMBER_LIST)}
  end
  test.report("summary_string:") do
    LOOP_COUNT.times {|x|summary_string(TEST_STRING_LIST)}
  end
end

出力

Rehearsal ---------------------------------------------------
summary_number:   0.015000   0.000000   0.015000 (  0.011001)
summary_string:   0.016000   0.000000   0.016000 (  0.020001)
------------------------------------------ total: 0.031000sec

                      user     system      total        real
summary_number:   0.016000   0.000000   0.016000 (  0.006000)
summary_string:   0.015000   0.000000   0.015000 (  0.019001)
[Finished in 0.2s]