装饰器可以简化复杂的程序,下面是一个利用装饰器记录函数花费时间功能
import time
def record_time(func):
def record_fun(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
print('time cost: {}s'.format(round(time.time() - t0, 4)))
return result
return record_fun
@record_time
def sleep_time(x, y):
time.sleep(x)
return x + y
sleep_time(1, 2)
# time cost: 1.0005s
# 3