装饰器应用(计算函数的执行时间)

#_author:Administrator
#date:2019/11/2
#优化
#先把展示时间的函数加载进内存
import time
def show_time(f):
def inner():
start=time.time()
f()
end=time.time()
print('spend time:%s'%(end-start))
return inner
@show_time #此处的@show_time相当于function1=show_time(function1)
def function1():
print('excute function<<')
time.sleep(2)
function1()
print('---------------------')
@show_time
def function2():
print('excute function2<<')
time.sleep(2)
function2()
#function1=show_time(function1) 相当于返回inner
# 执行结果:
# excute function<<
# spend time:2.0004312992095947
# ---------------------
# excute function2<<
# spend time:2.0000228881835938


原文地址:https://www.cnblogs.com/startl/p/11781290.html