为了更好的测试自己编写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)