装饰器统计函数执行总时间
from functools import wraps
def time_func(func):
elapse_time = 0.
@wraps(func)
def newfunc(*args, **kwargs):
nonlocal elapse_time # 使用外部的变量
startTime = time.time()
result = func(*args, **kwargs)
elapse_time += time.time() - startTime
return result
newfunc.elapse_time = lambda: elapse_time
return newfunc
统计在该次执行中,函数被执行的总时间,nonlocal量的定义,是为了使第二次调用时时间不清零
@time_func
def count():
for i in range(100):
time.sleep(0.001)
count()
print(count.elapse_time())
[count() for i in range(3)]
print(count.elapse_time())
执行结果
0.1101679801940918
0.44211459159851074
本文介绍了一种使用Python装饰器来统计函数执行总时间的方法。通过定义一个装饰器,可以方便地为任意函数添加时间统计功能,而无需修改函数本身。文章提供了具体的代码实现,并演示了如何使用这个装饰器来获取函数的执行时间。
427

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



