简体   繁体   English

time.sleep()会停止所有执行吗?

[英]Does time.sleep() stop all executions?

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: 在我复杂的python程序中,当它运行时,我有一段代码每3秒执行一次,该代码将程序的进度打印为完成的百分比,如下所示:

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? time.sleep()函数会减慢我的程序速度吗? 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? 如果它使我的程序变慢,是否有更正确的方法每3秒将进度打印给我一次?

Yes, time.sleep will halt your program. 是的, time.sleep将暂停您的程序。

Use time.time in your loop and check when three seconds have passed. 在循环中使用time.time并检查是否经过了三秒钟。

time.sleep(seconds) will stop execution on the current thread. time.sleep(seconds)将停止在当前线程上执行。 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. 如果程序使用线程,则其他线程不应停止。

from time import time

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM