當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。