【发布时间】:2020-01-22 05:54:38
【问题描述】:
我需要测量我的代码的某些部分所花费的时间。在强大的服务器上执行我的代码时,我得到了 10 个不同的结果
我尝试比较用time.time()、time.perf_counter()、time.perf_counter_ns()、time.process_time() 和time.process_time_ns() 测量的时间。
import time
for _ in range(10):
start = time.perf_counter()
i = 0
while i < 100000:
i = i + 1
time.sleep(1)
end = time.perf_counter()
print(end - start)
我希望在执行相同的代码 10 次时,结果相同(结果的分辨率至少为 1 毫秒)例如。 1.041XX 而不是 1.030 秒 - 1.046 秒。
When executing my code on a 16 cpu, 32gb memory server I'm receiving this result:
1.045549364
1.030857833
1.0466020120000001
1.0309665050000003
1.0464690349999994
1.046397238
1.0309525370000001
1.0312070380000007
1.0307592159999999
1.046095523
Im expacting the result to be:
1.041549364
1.041857833
1.0416020120000001
1.0419665050000003
1.0414690349999994
1.041397238
1.0419525370000001
1.0412070380000007
1.0417592159999999
1.041095523
【问题讨论】:
-
@PatrickArtner 我不是在寻找平均时间,我只是在计算相同的时间,当我执行相同的代码部分以与上次迭代相同时。我不明白为什么有时会花更多的时间,有时会花更少的时间。
-
查看我的回答和 sleep() 的文档
标签: python python-3.x time