pythontimeelapsedtimeelapsed

Why does the elapsed time of a function slightly change with every run?


This is a piece of code that calculates the time elapsed to execute a for loop that sums the integers from 0 to 10000000 and prints the result.

# time elapsed:

import time

start = time.time()

sum = 0
for num in range(10000000):
    sum += num

print("sum = ", sum)

end = time.time()
diff = end - start
print("time elapsed = ", diff) 

My question is why does the time difference between the start time and end time change with every run. Here is the output from three consecutive runs of the same code: as you can see I get: 1.84, 1.91, and 1.97

#1
sum =  49999995000000
time elapsed =  1.8434970378875732

#2
sum =  49999995000000
time elapsed =  1.916696548461914

#3
sum =  49999995000000
time elapsed =  1.9736623764038086

Solution

  • In short, the operating system is in charge of choosing what programs to execute, in other words, the CPUs are constantly switching between different programs since the number of programs can be executed at the same time is limited to CPU resources. Your program consists of multiple commands, therefore, there is no guarantee that the time between two calls will always be the same because CPUs might be busy with other programs running in your computer in between them. Here are more details answered by Anis.