theactiveactor
theactiveactor

Reputation: 7554

Python execute a function for X seconds

I'm looking for a way for a function to take actions based on how long it has been executing. For example, my function would loop continuously until 5 seconds has elapsed, in which case it returns immediately. Any suggestions?

Upvotes: 1

Views: 2656

Answers (2)

Nicholas Knight
Nicholas Knight

Reputation: 16045

Another option is to use signal.alarm() with an appropriate signal handler, documented at http://docs.python.org/library/signal.html. A particular advantage to this approach is not having to check the time every time you loop, which may add significant overhead for small, tight loops.

Upvotes: 4

gimel
gimel

Reputation: 86362

Have you looked at time.clock() ?

time.clock()

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Using 'time.clock()' to measure time on Windows:

>>> import time
>>> def measure():
...     t0 = time.clock()
...     time.sleep(3)
...     return time.clock() - t0
... 
>>> measure()
2.9976609581514113
>>> 

Upvotes: 5

Related Questions