Does time.sleep() stop all executions?

喜欢而已 提交于 2020-07-23 11:32:31

问题


In my complex python program, when it's running, I have a piece of code that executes every 3 seconds that prints the program's progress as the percentage of the execution that's finished like so:

while len(dequeueingFinishedList)!=10:
    print(str(len(masterListCSV_RowsListFinished)/float(len(masterListCSV_RowsList))*100) + "% done.")
    time.sleep(3)

Is the time.sleep() function going to slow down my program? I read the that sleep function suspends execution. If it is slowing down my program, is there a more correct way of printing the progress to me every 3 seconds?


回答1:


from time import time

prev = time()
while True:
    now = time()
    if now - prev > 3:
        print 'report'
        prev = now
    else:
        pass
        # runs



回答2:


Yes, time.sleep will halt your program.

Use time.time in your loop and check when three seconds have passed.




回答3:


time.sleep(seconds) will stop execution on the current thread. Therefore, it will completely stop your program on that thread: nothing else will happen until those seconds pass.

You don't have to worry about this. If the program uses threading, then the other threads shouldn't halt.




回答4:


The proper way to do this is with signal

import signal

def handler(signum, frame):
    print i
    if i>100000000:
        raise Exception("the end")
    else:
        signal.alarm(3)      

signal.signal(signal.SIGALRM, handler)   
signal.alarm(3)     

i=0
while True:
   i+=1


来源:https://stackoverflow.com/questions/32572280/does-time-sleep-stop-all-executions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!