使用benchmark来计算代码执行的消耗时间,代码示例如下

require 'benchmark'

p Benchmark.measure { "a"*100_100_100 }
#<Benchmark::Tms:0x00007fbd9f0c47c0 @label="", @real=0.006699000019580126, @cstime=0.0, 
@cutime=0.0, @stime=0.0031030000000000016, @utime=0.0032460000000000128, @total=0.006349000000000014>

#说明,measure是benchmark中简单的计算时间的方法
#使用幽灵方法比使用普通方法要慢,因为在调用幽灵方法时,方法查找的路径一般要更长一些
class String
  def method_missing(method, *args)
    method == :ghost_reverse ? reverse : super
  end
end

require 'benchmark'

Benchmark.bm do |b|
  b.report 'Normal method' do
    1000000.times{ "abc".reverse }
  end

  b.report 'Ghost method' do
    1000000.times{ "abc".ghost_reverse }
  end
end

results matching ""

    No results matching ""