这是一段代码,用于计算执行 for 循环所用的时间,该循环将 0 到 10000000 的整数相加并打印结果。
# 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)
我的问题是为什么每次运行时开始时间和结束时间之间的时间差都会改变。这是相同代码的三个连续运行的输出:如您所见,我得到:1.84、1.91 和 1.97
#1
sum = 49999995000000
time elapsed = 1.8434970378875732
#2
sum = 49999995000000
time elapsed = 1.916696548461914
#3
sum = 49999995000000
time elapsed = 1.9736623764038086