为什么Python循环变慢?

我创建一个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同步更新

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值