以下哪项是最有效的

时间:2015-04-17 20:08:39

标签: ruby loops

如果我想从0到5打印x

6.times {|x| p x}

(0..5).each {|x| p x}

0.upto(5) {|x| p x}

for x in 0..5
  p x
end

2 个答案:

答案 0 :(得分:5)

benchmark/ips是一个更好的工具。

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("times") { 6.times {|x| } }
  x.report("range iteration") { (0..5).each {|x| } }
  x.report("upto") { 0.upto(5) {|x| } }
  x.report("for") do
    for x in 0..5
    end
  end
end

Ruby 2.2.0上的结果:

Calculating -------------------------------------
               times    88.567k i/100ms
     range iteration    88.519k i/100ms
                upto    86.749k i/100ms
                 for    84.118k i/100ms
-------------------------------------------------
               times      2.093M (± 0.2%) i/s -     10.451M
     range iteration      2.053M (± 0.4%) i/s -     10.268M
                upto      2.103M (± 0.2%) i/s -     10.583M
                 for      1.949M (± 0.2%) i/s -      9.758M

在这里循环一个空体是更好的主意,因为来自p的IO时间可能会使循环迭代次数相形见绌。结果,它足够接近无关紧要。

答案 1 :(得分:2)

您需要使用基准

之类的内容

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

require 'benchmark'
puts Benchmark.measure {6.times {|x| p x}}
puts Benchmark.measure {(0..5).each {|x| p x}}
puts Benchmark.measure {0.upto(5) {|x| p x}}

你会看到一个看起来像

的输出
1 ) 0.000000   0.000000   0.000000 (  0.000059)
1 ) 0.000000   0.000000   0.000000 (  0.000050)
3 ) 0.000000   0.000000   0.000000 (  0.000046)

现在您可以阅读有关基准 here

的更多信息

你可以用1000000次来尝试它几次以获得一个好的量具,现在结果会随着每个计算以及测试时计算机上运行的其他内容而改变