#Author:donghuiya #高阶函数+嵌套函数=装饰器 import time def timer(func): def deco(*args,**kwargs): start_time=time.time() func(*args,**kwargs) stop_time=time.time() print("the func run time is %s"%(stop_time-start_time)) return deco @timer #test1=timer(test1) 左test1相当于deco def test1(): time.sleep(3) print("this is test1") @timer #要更改deco def test2(name,age): print("test2",name,age) test1() test2("alex",22)
装饰器练习
本文介绍了一种使用Python装饰器来记录函数运行时间的方法。通过定义一个名为`timer`的装饰器,可以轻松地为任何函数添加计时功能。示例中展示了如何将此装饰器应用于两个不同的函数,并打印出它们的执行时间。

被折叠的 条评论
为什么被折叠?



