如何乘以基准

How to multiply a benchmark

假设我有这样的基准测试结果:

0.020000   0.000000   0.020000 (  0.020197)

我正在用类似

的东西创建它
Benchmark.bm do |x|
  x.report { run_a_method() }
end

这表示调用方法 foo 一次所需的时间。

我想生成一个基准测试,显示 运行ning foo 3 次的结果,但只需要调用该方法一次。

这可以通过简单地将第一个基准中的值乘以 3 来完成。

有什么办法吗?

编辑

我不是很欣赏评论说这是 "not a correct benchmark"。我认识到多次 运行 更准确,但这些是资源密集型测试,我只是预测多个 运行 的预期时间范围。

换句话说,我的用例只是为了创建对倍数 运行 时间的期望,而不是完全准确的期望。

正如您所建议的那样,外推的问题在于它会加剧您遇到的任何错误。 运行 单个基准测试的 N 轮往往会消除任何违规行为。 运行 1 轮并乘以 N 实际上会放大任何不规则性。

所以简短的回答是你不能。您需要 运行 多次测试才能更好地了解性能。如果这些测试需要很长时间才能完成 运行,您要么不得不承担成本,要么想办法更快地 运行 使它们正常运行,或者以某种方式并行进行。

我自己想出来了。

最初我尝试了以下方法:

report = Benchmark.bm do |x|  
  x.report { sleep.0.5 }
end
# => report is an array with     
#    1 element

report * 2
# => shows an array with 2 elements
#    (the first is duplicated)

但我最终还是想试试

report[0] * 2

这具有使基准值翻倍的预期效果。

例如,如果 report 变量指向

[#<Benchmark::Tms:0x0055fcba149030
@label="", 
@real=0.5001437529999748, 
@cstime=0.0, @cutime=0.0, 
@stime=0.0, @utime=0.0, @total=0.0>]

运行 puts (report[0] * 2) 显示

  0.000000   0.000000   
0.000000 (  1.000288)
=> nil

这是我想要的乘积值。