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

下面我们来测量"a"*1_000_000的执行时间:

require 'benchmark'

puts Benchmark.measure { "a"*1_000_000 }

结果如下(我的电脑是i3,linux mint操作系统):

xiongxin@rubyonrails ~/ruby/6-7 $ ruby benchmark-t.rb 
  0.000000   0.000000   0.000000 (  0.000599)

下面Benchmark模块提供measure方法的代码

  def measure(label = "") # :yield:    
    t0, r0 = Process.times, Time.now
    yield
    t1, r1 = Process.times, Time.now
    Benchmark::Tms.new(t1.utime  - t0.utime,
                       t1.stime  - t0.stime,
                       t1.cutime - t0.cutime,
                       t1.cstime - t0.cstime,
                       r1 - r0,
                       label)
  end

注释:
Process.times 返回 Tms structure,包括用户和系统CPU时间

  t = Process.times
  #其实现在 t = [ t.utime, t.stime, t.cutime, t.cstime ]

我们来一个一个分析他的返回值:
Struct::Tms#cstime() #=> Float
Returns the number of seconds of system CPU time consumed by waited-for, terminated child processes, i.e. the sum of their Struct::Tms#stime and Struct::Tms#cstime values. Returns 0.0 on Windows.

Struct::Tms#cutime() #=> Float
Returns the number of seconds of user CPU time consumed by waited-for, terminated child processes, i.e. the sum of their Struct::Tms#utime and Struct::Tms#cutime values. Returns 0.0 on Windows.

Struct::Tms#stime() #=> Float
Returns the number of seconds of system CPU time consumed by the calling process.

Struct::Tms#utime() #=> Float
Returns the number of seconds of user CPU time consumed by the calling process.


天赢金创
338 声望21 粉丝

天赢金创,天赢金创,天赢金创,天赢金创,天赢金创,天赢金创天赢金创,天赢金创


« 上一篇
Enumerators
下一篇 »
Rails 常见路由

引用和评论

0 条评论