python - python 中 timeit.timeit() 函数的拆解

标签 python timeit teardown

有没有办法在 python 中为 timeit.timeit() 函数指定拆卸? 我知道有关于“声明”和“设置”的争论,但我还没有找到执行拆卸的好方法。

在我的“声明”中包含拆解代码会影响我尝试计时的代码片段的计时。我需要拆解以释放硬件资源,以便我可以使用 timeit 模块中的重复功能。

最佳答案

不,没有真正好的方法来做到这一点。看着 source ,您可能需要将 Timer 类子类化,用新版本替换它们的 self.inner

例如:

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

请注意,由于您一次只能为单个测试计时,因此您不会以这种方式获得很好的计时。不幸的是,我不够聪明,无法想出一种方法来一次为多个测试计时,并使用需要为每个调用的拆卸函数。

或者,您可以猴子修补 _template_func ,基本上只是在 创建计时器之前从上面复制我的 _func 。如果您想尽可能干净地完成此操作,也许使用 mock 进行修补/取消修补将是一个好主意(尽管您也可以自己轻松完成)。

请注意,我们在这里尝试了一些内部的东西——这个答案可能会在没有警告的情况下随时中断,并且它可能只适用于 CPython,因为这些都没有被记录下来。

关于python - python 中 timeit.timeit() 函数的拆解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22639305/

相关文章:

python - Django Rest Framework 的测试请求无法由其自己的 Request 类解析

python - Python 中的 %timeit 是什么?

python - 在 cython 函数上使用 timeit

unit-testing - Elixir /ExUnit : passing context from testcase to teardown/cleanup method (on_exit) possible?

python - 转换日期Python

Python 获取最近的文件FTP

python - Apache2 CGI 配置

python - timeit 返回什么时间单位?

java - 退出线程时如何执行代码

c# - 如何在每次 NUnit 测试后运行方法(甚至在拆卸时失败)