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)