一,原来有一个函数,要统计函数耗时。原来执行方式task(),增加的功能要解耦,实现功能后,执行方式还是task()
def task(): time.sleep(3) print("sleep 3s")
二,耗时功能实现,并封装成一个函数
def wrapper(func): start_time = time.time() # func函数必须在这里执行,所以必须是fuc() res = func() end_time = time.time() elapse = datetime.timedelta(seconds=int(end_time - start_time)) print("{} 耗时:{}".format(func.__name__, elapse)) # wrapper需要把func返回值透传出去 return res
三,把封装好的新函数替透传出去,调用时实现功能
def my_dec(func):
def wrapper():
start_time = time.time()
res = func()
end_time = time.time()
elapse = datetime.timedelta(seconds=int(end_time - start_time))
print("{} 耗时:{}".format(func.__name__, elapse))
return res
return wrapper
task = my_dec(task)
task()
最外层这个函数的意义:
四,python里的语法糖,用@代替task重新赋值
def my_dec(func): def wrapper(): start_time = time.time() res = func() end_time = time.time() elapse = datetime.timedelta(seconds=int(end_time - start_time)) print("{} 耗时:{}".format(func.__name__, elapse)) return res return wrapper # @my_dec相当于task=my_dec(task) @my_dec def task(): time.sleep(3) print("sleep 3s") task()