开发者

python -> time a while loop has been running

i have a loop that runs for up to a few h开发者_开发百科ours 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?


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)


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


There's a very hacky way to do this by using time.asctime(). You store the asctime before entering the while loop and somewhere in the loop itself. Calculate the time difference between the stored time and the current time and if that difference is 10 seconds, then update the stored time to the current time and print that it's been running.

However, that's a very hacky way to do it as it requires some twisted and boring math.

If your aim is to check the runtime of a specific algorithm, then you're better off using the timeit module

Hope this Helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜