Ruby 2.5.0 リファレンスマニュアル > ライブラリ一覧 > benchmarkライブラリ > Benchmarkモジュール > bm
bm(label_width = 0, *labels) {|rep| ... } -> [Benchmark::Tms]
[permalink][rdoc]Benchmark.#benchmark メソッドの引数を簡略化したものです。
Benchmark.#benchmark メソッドと同様に働きます。
require 'benchmark'
n = 50000
Benchmark.bm do |x|
x.report { for i in 1..n; a = "1"; end }
x.report { n.times do ; a = "1"; end }
x.report { 1.upto(n) do ; a = "1"; end }
end
#=>
#
# user system total real
# 1.033333 0.016667 1.016667 ( 0.492106)
# 1.483333 0.000000 1.483333 ( 0.694605)
# 1.516667 0.000000 1.516667 ( 0.711077)
以下のようにも書けます。
require 'benchmark'
n = 50000
Benchmark.bm(7) do |x|
x.report("for:") { for i in 1..n; a = "1"; end }
x.report("times:") { n.times do ; a = "1"; end }
x.report("upto:") { 1.upto(n) do ; a = "1"; end }
end
#=>
# user system total real
# for: 1.050000 0.000000 1.050000 ( 0.503462)
# times: 1.533333 0.016667 1.550000 ( 0.735473)
# upto: 1.500000 0.016667 1.516667 ( 0.711239)
集計を付けた場合
require 'benchmark'
n = 50000
Benchmark.bm(7, ">total:", ">avg:") do |x|
tf = x.report("for:") { for i in 1..n; a = "1"; end }
tt = x.report("times:") { n.times do ; a = "1"; end }
tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
[tf + tt + tu, (tf + tt + tu) / 3]
end
#=>
# user system total real
# for: 0.001467 0.004727 0.006194 ( 0.006193)
# times: 0.003814 0.000000 0.003814 ( 0.003814)
# upto: 0.003855 0.000003 0.003858 ( 0.003859)
# >total: 0.009136 0.004730 0.013866 ( 0.013867)
# >avg: 0.003045 0.001577 0.004622 ( 0.004622)
[SEE_ALSO] Benchmark.#benchmark