doge
doge

Reputation: 132

Which of the following is the most efficient

If I would like to print x from 0 to 5

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

Upvotes: 3

Views: 88

Answers (2)

Chris Heald
Chris Heald

Reputation: 62648

benchmark/ips is a better tool for this.

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

Results on 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

Looping an empty body is the better idea here, since the IO time from p will likely dwarf the loop iteration times. Result-wise, it's close enough to not matter.

Upvotes: 5

MZaragoza
MZaragoza

Reputation: 10111

You will need to use something like Benchmark

The Benchmark module provides methods to measure and report the time used to execute Ruby code.

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}}

and you are going to see a output that looks like

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)

now you can read more about benchmark here

you can have to try it a couple of many of times with 1000000.times to get a good gage, now the results are going to change with every compute and with what else is running on that computer at the time of the test

Upvotes: 2

Related Questions