user system total real sort! 0.8800000.0100000.890000 ( 0.894623) sort 0.8900000.0100000.900000 ( 0.898280)
Benchmark.benchmark
假設需要比較後的平均花費時間、總共時間,可以這麼處裡:
1 2 3 4 5 6 7 8 9 10
require'benchmark' include Benchmark # we need the CAPTION and FORMAT constants
num = 5000000 Benchmark.benchmark(CAPTION, 7, "111%r", ">total:", ">avg:") do|x| tf = x.report("for:") { for i in1..num; a = "1"; end } tt = x.report("times:") { num.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(num) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
output:
1 2 3 4 5 6
user system total real for:0.3500000.0000000.350000 ( 0.349957) times:0.3400000.0000000.340000 ( 0.341593) upto:0.3400000.0100000.350000 ( 0.348147) >total:1.0300000.0100001.040000 ( 1.039697) >avg:0.3433330.0033330.346667 ( 0.346566)