在没有Benchmark或时间的Ruby中测量用户时间或系统时间

Flo*_*ilz 5 ruby time benchmarking measurement systemtime

由于我现在正在做一些时间测量,我想知道是否可以在不使用Benchmark类或命令行实用程序的情况下测量用户时间或系统时间time.

使用Time该类仅显示挂钟时间,而不是系统和用户时间,但我正在寻找具有相同灵活性的解决方案,例如

time = TimeUtility.now
# some code
user, system, real = TimeUtility.now - time
Run Code Online (Sandbox Code Playgroud)

原因是我不知何故不喜欢Benchmark,因为它不能只返回数字(编辑:我错了 - 它可以.见下面的答案.).当然,我可以解析输出,但这感觉不对.time来自*NIX系统的实用程序也应该解决我的问题,但我想知道是否已经在Ruby中实现了某种包装器,所以我不需要自己进行这些系统调用.

非常感谢!

Flo*_*ilz 8

我重新阅读了Benchmark文档,发现它有一个名为的方法measure.这个方法完全符合我的要求:测量代码所需的时间并返回一个包含用户时间,系统时间,子系统时间等的对象.它就像

require 'benchmark'
measurement = Benchmark.measure do
  # your code goes here
end
Run Code Online (Sandbox Code Playgroud)

在此过程中,我发现您可以将自定义行添加到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
Run Code Online (Sandbox Code Playgroud)

结果如下所示:

             user     system      total        real
sum:     2.700000   0.000000   2.700000 (  2.706234)
avg:     0.270000   0.000000   0.270000 (  0.270623)
Run Code Online (Sandbox Code Playgroud)