[英]How do I use timeit module inside a decorator
我正在创建一个装饰器来主要对它装饰的任何timeit
进行计时。 而且我无法正确处理。 引发max recursion depth error
。 有人可以帮我理解它为什么会发生以及如何实现这个 timeit 实现。 我不想使用time
模块
import timeit
from functools import wraps
def tool(func):
"""Include debug statement and timeit setup"""
@wraps(func)
def wrapper(*args):
print func.__doc__, args,
res = func(*args)
print res
CODE = "func{args}".format(args=args)
times = timeit.repeat(
stmt=CODE,
setup="from __main__ import {func} as func".format(func=func.__name__),
repeat=3, number=10000)
print times
return wrapper
我提到的问题是在设置中,执行该导入会为您提供已经装饰的 function,当再次执行时执行导入并获取装饰的 function 并继续执行导入并继续执行直到它炸毁堆栈。 .我们不希望那样。
The timeit module can also take function as its stmt, so with just building a lambda function it solve the problem and we can use the undercoated function that way
stmt 和 setup 参数也可以采用无需 arguments 即可调用的对象。 这会将对它们的调用嵌入到计时器 function 中,然后由 timeit() 执行。 请注意,在这种情况下,由于额外的 function 调用,时序开销会稍大一些。
import timeit
from functools import wraps
def tool(func):
"""Include debug statement and timeit setup"""
@wraps(func)
def wrapper(*args):
print(func.__doc__, args)
res = func(*args)
print(res)
times = timeit.repeat(
stmt=lambda: func(*args),
repeat=3, number=10000)
print(times)
return wrapper
和快速测试
>>> @tool
def fun():
return 42
>>> fun()
None ()
42
[0.0013318000000026586, 0.0013294000000314554, 0.0013452000000597764]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.