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