[英]Teardown for timeit.timeit() function in python
Is there a way to specify a teardown for the timeit.timeit() function in python? 有没有办法在python中指定timeit.timeit()函数的拆解? I know there are arguments for 'Statement' and 'Setup', but I haven't found a good way to perform a teardown. 我知道有'声明'和'设置'的论据,但我没有找到一个好的方法来执行拆解。
Including the teardown code in my 'Statment' is skewing my timing for the code snippet I am trying to time. 在我的'Statment'中包含拆解代码会使我想要时间的代码片段的时间偏差。 I require a teardown in order to release the hardware resources so that i can use the repeat function from the timeit module. 我需要拆机才能释放硬件资源,以便我可以使用timeit模块中的repeat功能。
Nope, there's no really good way to do this. 不,没有真正好的方法可以做到这一点。 Looking at the source , you'll likely need to subclass the Timer class replacing their self.inner
with a new version. 查看源代码 ,您可能需要将Timer类子类self.inner
使用新版本替换self.inner
。
eg: 例如:
import inspect
import timeit
class MyTimer(timeit.Timer):
def __init__(self, stmt="pass", setup="pass", teardown=None, timer=timeit.default_timer):
timeit.Timer.__init__(self, stmt, setup, timer)
# Pull the actual function to time off the original `self.inner` function.
time_func = inspect.getargspec(self.inner).defaults[0]
# It gets added as a keyword so that lookup in the
# current namespace is really fast.
def _func(_it, _timer, _func=time_func):
setup()
total = 0.0
for _i in _it:
_t0 = _timer()
_func()
_t1 = timer()
total += _t1 - _t0
if teardown:
teardown()
return total
self.inner = _func
Beware though that you won't get as good of a timing this way since you're limited to timing a single test at a time. 请注意,由于您仅限于一次测试一次测试,因此您不会以这种方式获得好时机。 Unfortunately, I'm not clever enough to figure out a way to time multiple tests at a time with a teardown function that needs to be called for each one . 不幸的是,我并不聪明,无法找到一种方法来计算多次测试的时间,并且需要为每个测试调用一个拆卸功能。
Alternatively, you could monkey patch the _template_func
, basically just copying my _func
from above before you create your timer. 或者,您可以_template_func
,基本上只是在创建计时器之前从上面复制我的_func
。 If you wanted to do this as cleanly as possible, maybe using mock
to do the patching/unpatching would be a good idea (although you could also do it yourself without much trouble). 如果你想尽可能干净地做这件事,也许使用mock
来修补/取消修补将是一个好主意(虽然你也可以自己做,没有太多麻烦)。
Note, we've played around with internal stuff here -- This answer could break at any time without warning, and it may only work on CPython since none of this is documented. 注意,我们在这里玩过内部的东西 - 这个答案可能会在没有任何警告的情况下随时中断,并且它可能仅适用于CPython,因为这些都没有记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.