Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python -> time a while loop has been running

i have a loop that runs for up to a few hours at a time. how could I have it tell me how long it has been at a set interval?

just a generic...question

EDIT: it's a while loop that runs permutations, so can i have it print the time running every 10 seconds?

like image 510
tekknolagi Avatar asked Jan 18 '11 02:01

tekknolagi


People also ask

How do you break a loop after some time Python?

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

What is while () in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand.


2 Answers

Instead of checking the time on every loop, you can use a Timer object

import time
from threading import Timer

def timeout_handler(timeout=10):
    print time.time()
    timer = Timer(timeout, timeout_handler)
    timer.start()

timeout_handler()
while True:
    print "loop"
    time.sleep(1)
like image 150
kefeizhou Avatar answered Sep 28 '22 04:09

kefeizhou


As noted, this is a little bit of a nasty hack, as it involves checking the time every iteration. In order for it to work, you need to have tasks that run for a small percentage of the timeout - if your loop only iterates every minute, it won't print out every ten seconds. If you want to be interrupted, you might consider multithreading, or preferably if you are on linux/mac/unix, signals. What is your platform?

import time

timeout = 10
first_time = time.time()
last_time = first_time
while(True):
    pass #do something here
    new_time = time.time()
    if  new_time - last_time > timeout:
        last_time = new_time
        print "Its been %f seconds" % (new_time - first_time)

Output:

Its been 10.016000 seconds
Its been 20.031000 seconds
Its been 30.047000 seconds
like image 34
fmark Avatar answered Sep 28 '22 05:09

fmark