我重新阅读了 Benchmark 文档,发现它有一个名为measure
. 这个方法正是我想要的:测量你的代码需要的时间并返回一个包含用户时间、系统时间、儿童系统时间等的对象。它很简单
require 'benchmark'
measurement = Benchmark.measure do
# your code goes here
end
在此过程中,我发现您可以将自定义行添加到 Benchmark 输出。您可以使用它来获得两全其美(自定义时间测量和最后的良好输出),如下所示:
require 'benchmark'
measurements = []
10.times { measurements << Benchmark.measure { 1_000_000.times { a = "1" } } }
# measurements.sum or measurements.inject(0){...} does not work, since the
# array contains Benchmark instances, which cannot be coerced into Fixnum's
# Array#sum will work if you are using Rails
sum = measurements.inject(nil) { |sum, t| sum.nil? ? sum = t : sum += t }
avg = sum / measurements.size
# 7 is the width reserved for the description "sum:" and "avg:"
Benchmark.bm(7, "sum:", "avg:") do |b|
[sum, avg]
end
结果将如下所示:
user system total real
sum: 2.700000 0.000000 2.700000 ( 2.706234)
avg: 0.270000 0.000000 0.270000 ( 0.270623)