python 用来计算函数运行时间的装饰器

为了更好的测试自己编写Python代码的性能和运行时间,特意搞了一个装饰器来监控函数的运行时间。
代码如下

import datetime
from functools import wraps


class Timeit:
    def __init__(self, fn=None):
        wraps(fn)(self)

    def __call__(self, *args, **kwargs):
        start = datetime.datetime.now()
        ret = self.__wrapped__(*args, **kwargs)
        cost = datetime.datetime.now() - start
        print(cost)
        return ret

    def __enter__(self):
        self.start = datetime.datetime.now()

    def __exit__(self, *args):
        cost = datetime.datetime.now() - self.start
        print(cost)

你可能感兴趣的:(python 用来计算函数运行时间的装饰器)