我创建一个while
循环和print
每个循环的时间戳。一开始我每秒获得约33个循环的性能。但是,时间越长,速度越慢。在3分钟时,我每秒显示2个循环。我尝试使用threading.Timer
它来代替,但是它做同样的事情。我知道计算的内存和复杂性可能是一个问题,但在这种情况下似乎并非如此。
我想在几个小时内运行代码,如何避免性能不足?您的帮助将不胜感激。
<span style="color:#333333"><code style="margin-left:0px">import time
while(True):
print(int(round(time.time() * 1000)))
</code></span>
输出量
<span style="color:#333333"><code style="margin-left:0px">1556756682157
1556756682216
1556756682240
1556756682269
1556756682296
1556756682324
1556756682358
1556756682387
1556756682415
1556756682441
1556756682470
1556756682501
1556756682556
... // After 3 minutes
1556756860002
1556756860884
1556756861240
1556756861669
1556756862596
1556756863324
1556756863858
1556756864387
</code></span>
解决方案
根据测试,打印可以大大降低循环速度。删除打印件,您的速度不应再降低那么快。参见下面的示例:
<span style="color:#333333"><code style="margin-left:0px">from time import time
start = time()
for i in range(1_000_000):
print(i)
print(f'run time for printing: {time() - start}')
start = time()
for _ in range(1_000_000):
pass
print(f'run time for no printing: {time() - start}')
this is what it printed:
# a ton of numbers above this line from printing
run time for printing: 7.047402858734131
run time for no printing: 0.0870048999786377</code></span>
本文首发于Python黑洞网,csdn同步更新