I'm looking for a way for a function to take actions based on how long it has been executing. For example, my function开发者_Go百科 would loop continuously until 5 seconds has elapsed, in which case it returns immediately. Any suggestions?
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
>>>
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.
精彩评论