Rafi
Rafi

Reputation: 1922

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:

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?

Upvotes: 0

Views: 6550

Answers (4)

Zizouz212
Zizouz212

Reputation: 4998

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.

Upvotes: 4

dawg
dawg

Reputation: 104092

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

Upvotes: 1

taesu
taesu

Reputation: 4580

from time import time

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

Upvotes: -1

orlp
orlp

Reputation: 117846

Yes, time.sleep will halt your program.

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

Upvotes: 2

Related Questions