Which of the following is most effective
2 answers
testmark / ips is the best 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 in 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
An empty body loop is the best idea here, as the I / O out time p
will likely overshadow the loop iteration times. The result is close enough not to matter.
+5
source to share
You will need to use something like Benchmark
The Benchmark module provides methods for measuring and reporting the time taken to run 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 will see a result 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 need to try a few times with 1,000,000. To get a good sensor, now the results will change with each calculation and with what else is running on that computer during the test
+2
source to share