Post

Rubyで処理速度の平均を計測したい

計測

require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants nn = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..nn; a = "1"; end } tt = x.report("times:") { nn.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(nn) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end

結果

user system total real for: 0.380000 0.000000 0.380000 ( 0.374220) times: 0.370000 0.000000 0.370000 ( 0.375088) upto: 0.370000 0.000000 0.370000 ( 0.368562) >total: 1.120000 0.000000 1.120000 ( 1.117870) >avg: 0.373333 0.000000 0.373333 ( 0.372623)
リンク先のサンプルをそのまま実行すると、Error: Cannot find local context. Did you use `binding.pry`? なるエラーが発生する

Pryのコンソールで使えない変数 - Qiita

Module: Benchmark (Ruby 2.5.0)

This post is licensed under CC BY 4.0 by the author.