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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章