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


Ruby Benchmark模块用法及代码示例


本文简要介绍ruby语言中 Benchmark模块 的用法。

Benchmark 模块提供了测量和报告用于执行 Ruby 代码的时间的方法。

  • 测量构造由表达式 "a"*1_000_000_000 给出的字符串的时间:

    require 'benchmark'
    
    puts Benchmark.measure { "a"*1_000_000_000 }

    在我的机器(i5 1.7 GHz 上的 OSX 10.8.3)上,这会生成:

    0.350000   0.400000   0.750000 (  0.835234)

    此报告显示用户 CPU 时间、系统 CPU 时间、用户和系统 CPU 时间的总和以及经过的实时时间。时间单位是秒。

  • 使用 bm 方法依次做一些实验:

    require 'benchmark'
    
    n = 5000000
    Benchmark.bm do |x|
      x.report { for i in 1..n; a = "1"; end }
      x.report { n.times do   ; a = "1"; end }
      x.report { 1.upto(n) do ; a = "1"; end }
    end

    结果:

        user     system      total        real
    1.010000   0.000000   1.010000 (  1.014479)
    1.000000   0.000000   1.000000 (  0.998261)
    0.980000   0.000000   0.980000 (  0.981335)
  • 继续前面的示例,在每个报告中放置一个标签:

    require 'benchmark'
    
    n = 5000000
    Benchmark.bm(7) do |x|
      x.report("for:")   { for i in 1..n; a = "1"; end }
      x.report("times:") { n.times do   ; a = "1"; end }
      x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
    end

结果:

              user     system      total        real
for:      1.010000   0.000000   1.010000 (  1.015688)
times:    1.000000   0.000000   1.000000 (  1.003611)
upto:     1.030000   0.000000   1.030000 (  1.028098)
  • 某些基准测试的时间取决于项目的运行顺序。这些差异是由于内存分配和垃圾收集的成本造成的。为避免这些差异,提供了 bmbm 方法。例如,比较对浮点数数组进行排序的方法:

    require 'benchmark'
    
    array = (1..1000000).map { rand }
    
    Benchmark.bmbm do |x|
      x.report("sort!") { array.dup.sort! }
      x.report("sort")  { array.dup.sort  }
    end

    结果:

    Rehearsal -----------------------------------------
    sort!   1.490000   0.010000   1.500000 (  1.490520)
    sort    1.460000   0.000000   1.460000 (  1.463025)
    -------------------------------- total: 2.960000sec
    
                user     system      total        real
    sort!   1.460000   0.000000   1.460000 (  1.460465)
    sort    1.450000   0.010000   1.460000 (  1.448327)
  • 使用 benchmark 方法报告具有唯一标签的连续实验的统计信息:

    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.950000   0.000000   0.950000 (  0.952039)
    times:    0.980000   0.000000   0.980000 (  0.984938)
    upto:     0.950000   0.000000   0.950000 (  0.946787)
    >total:   2.880000   0.000000   2.880000 (  2.883764)
    >avg:     0.960000   0.000000   0.960000 (  0.961255)

相关用法


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