為了更好的測試自己編寫Python代碼的性能和運行時間蔼卡,特意搞了一個裝飾器來監(jiān)控函數(shù)的運行時間。
代碼如下
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)