简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM