示例
"""
程序运行计时工具
"""
import signal
class TimeoutException(Exception):
def __str__(self) -> str:
return "程序运行超时"
def timeout_handler(signum, frame):
"""
超时后执行的方法
:param signum:
:param frame:
:return:
"""
raise TimeoutException
def set_timeout(func, timeout: int, *args, **kwargs):
"""
给方法设置超时时间
:param func:
:param timeout:
:return:
"""
assert isinstance(timeout, int) and timeout > 0, "超时时间只能为非零正整数"
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout)
try:
res = func(*args, **kwargs)
finally:
signal.alarm(0)