Skip to main content
 首页 » 编程设计

Python 执行一个函数 X 秒

2025年05月04日16qlqwjy

我正在寻找一种方法,让函数根据执行时间长短采取行动。例如,我的函数会连续循环直到 5 秒过去,在这种情况下它会立即返回。有什么建议吗?

请您参考如下方法:

你看过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.

在 Windows 上使用“time.clock()”测量时间:

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