Python & # 8594; while cycle time

I have a loop that runs up to several hours at a time. how could I tell me how much time has passed at a given interval?

just a general question ...

EDIT: is this a while loop that triggers permutations, so can I print out the time every 10 seconds?

+6
python loops time while-loop permutation
source share
3 answers

Instead of checking the time on each cycle, you can use the 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) 
+8
source share

As already noted, this is a bit of a nasty hack, as it involves checking the time for each iteration. For it to work, you need to have tasks that are completed within a small percentage of the timeout - if your loop is repeated only every minute, it will not be displayed every ten seconds. If you want to be interrupted, you can think of multithreading or, if you want, 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 
+2
source share

There is a very hacky way to do this using time.asctime (). You save 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 this difference is 10 seconds, then update the stored time to the current time and print it.

However, this is a very hacky way to do this, as it requires some perverse and boring math.

If your goal is to check the execution time of a particular algorithm, then you better use the timeit module

Hope this helps

+1
source share

All Articles