这是一段代码,用于计算执行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
答案 0 :(得分:0)