当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Benchmark.benchmark用法及代码示例


本文简要介绍ruby语言中 Benchmark.benchmark 的用法。

用法

benchmark(caption = "", label_width = nil, format = nil, *labels) { |report| ... }

使用 Benchmark::Report 对象调用块,该对象可用于收集和报告单个基准测试的结果。为每行上的标签保留label_width 前导空格。在报告顶部打印caption,并使用format 格式化每一行。 (注意:caption 必须包含终止换行符,请参阅默认的 Benchmark::Tms::CAPTION 示例。)

返回 Benchmark::Tms 对象的数组。

如果块返回 Benchmark::Tms 对象的数组,这些将用于格式化额外的输出行。如果给定labels 参数,这些参数用于标记这些额外的行。

Note :其他方法为此提供了一个更简单的接口,并且适用于几乎所有的基准测试要求。请参阅 Benchmark 中的示例,以及 bm bmbm 方法。

例子:

require 'benchmark'
include Benchmark          # we need the CAPTION and FORMAT constants

n = 5000000
Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
  tf = x.report("for:")   { for i in 1..n; a = "1"; end }
  tt = x.report("times:") { n.times do   ; a = "1"; end }
  tu = x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
  [tf+tt+tu, (tf+tt+tu)/3]
end

生成:

              user     system      total        real
for:      0.970000   0.000000   0.970000 (  0.970493)
times:    0.990000   0.000000   0.990000 (  0.989542)
upto:     0.970000   0.000000   0.970000 (  0.972854)
>total:   2.930000   0.000000   2.930000 (  2.932889)
>avg:     0.976667   0.000000   0.976667 (  0.977630)

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Benchmark.benchmark。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。