I've just started programming in Ruby. This is my code:
numbers = Array (1..100)
start = Time.now
sum = numbers.inject(0) { |sum, num| sum num }
puts "sum equals: #{sum}"
time_taken = (Time.now - start) * 1000 * 1000
puts "time taken to execute #{time_taken}"
Why does this code return a different execution time every time I run it?
I mean first time it was:
time taken to execute this: 20.593
second:
time taken to execute this: 27.184
third:
time taken to execute this: 22.516
CodePudding user response:
Why does this code return a different execution time every time I run it?
Because your computer doesn't perform the exact same physical task every time it runs.
Maybe the data happened to be stored in slightly more/less efficient location on the RAM? Maybe your computer was too hot/cold, so performed differently. Maybe you also have 20 StackOverflow tabs open, which was using up system resources :D
Plus, in order to get a more accurate benchmark of how quickly some code runs, you need to decrease the error margin by performing the same operation lots of times.
I would recommend trying the benchmark-ips library if you wish to get some more reliable measurements of your code's performance.
