Python限制函数运行时间,记录函数运行时间的装饰器

平时会碰到一些实时项目,有些函数必须要在某一时限完成,所以必须要加入一些手段去监控函数的运行时间,下面的装饰器time_limit提供了这么一个功能,如果函数未能在规定时间内完成,则会抛出TimeoutError。
log_time_delta可以对函数运行时间进行一个记录。

from functools import wraps
from threading import Timer
import time
from datetime import datetime


def log_time_delta(func):
    @wraps(func)
    def deco():
        start = datetime.now()
        res = func()
        end = datetime.now()
        delta = end - start
        print("func runed ", delta)
        return res
    return deco


def time_limit(interval):
    @wraps(func)
    def deco(func):
        def time_out():
            raise TimeoutError()

        @wraps(func)
        def deco(*args, **kwargs):
            timer = Timer(interval, time_out)
            timer.start()
            res = func(*args, **kwargs)
            return res
        return deco
    return deco

@log_time_delta
def t():
    time.sleep(2)

@time_limit(2)
def tl():
    time.sleep(5)

t()
tl()

输出结果为:

func runed  0:00:02.000159
Exception in thread Thread-6:
Traceback (most recent call last):
  File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:\Python35\lib\threading.py", line 1180, in run
    self.function(*self.args, **self.kwargs)
  File "E:/prj/gevent_/time_util.py", line 32, in time_out
    raise TimeoutError()
TimeoutError
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章