爲什麼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同步更新

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章