python练习题之一个记录函数运行的装饰器

 
1.写一个装饰器,查看函数执行的时间


import datetime
import time
def jishi(fun):
def warper():
start_time = datetime.datetime.now()
fun()
end_time = datetime.datetime.now()
haoshi = (end_time-start_time).total_seconds()
print("函数运行耗时{}".format(haoshi))
return warper()

@jishi
def yunsuan():
time.sleep(2)
for x in range(100):
print(x)
yunsuan()


总结:总体思想就是 用函数运行后的当地时间减去函数运行前的当地时间。关于装饰器为什么要用双层函数嵌套,是因为装饰器的本意是原函数的代码和调用方式,所以要求warper连同原函数和增加的功能封装在一起

一起返回。

猜你喜欢

转载自www.cnblogs.com/chaojiyingxiong/p/9247284.html