Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Python loop slowingdown?

I create a while loop and print the timestamp on every loop. At the beginning I got a performance of about 33 loops by second. However, longer it takes, slower it gets. At 3 minutes, I have a performance of 2 loops by second. I tried to use threading.Timer instead, but it does the same thing. I am aware that Memory and Complexity of calculations can be an issue, but it doesn't seem to be the case in that scenario.

How can I avoid that lack of performance as I want to run the code for hours? Your help would be really appreciated.

import time

while(True):
    print(int(round(time.time() * 1000)))

Output

1556756682157
1556756682216
1556756682240
1556756682269
1556756682296
1556756682324
1556756682358
1556756682387
1556756682415
1556756682441
1556756682470
1556756682501
1556756682556
... // After 3 minutes
1556756860002
1556756860884
1556756861240
1556756861669
1556756862596
1556756863324
1556756863858
1556756864387
like image 320
G33kMan Avatar asked Apr 02 '26 16:04

G33kMan


1 Answers

Base on test done here, the print can considerably slow down your loop. Remiove the print and your speed shouldn't decrease that fast anymore. See below the example:

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
like image 113
Jonathan Gagne Avatar answered Apr 04 '26 09:04

Jonathan Gagne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!