【问题标题】:How to pass current object reference(self) to the Timer class of timeit module?如何将当前对象引用(self)传递给timeit模块的Timer类?
【发布时间】:2010-09-13 06:32:25
【问题描述】:

我正在尝试将当前对象引用(即 self)传递给 timeit 模块的 Timer 类,但不知何故我不知道该怎么做。我试图在 timeit 文档中找到它,但我找不到它。我已将我的代码附在这个问题上。

from timeit import Timer
import time  
import math

class PollingDemo(Thread):

    def __init__(self):
        pass

    def looper(self):

        while 1:
            try:
                T = Timer("self.my_func()")
                #T = Timer("polling.my_func()", "from __main__ import polling")
                time_elapsed = T.timeit(1)

                if math.ceil(time_elapsed) == 1:
                    print "Process is sleeped for 1 sec"
                    time.sleep(1)

            except KeyboardInterrupt:
                return

    def my_func(self):
        pass

if __name__ == '__main__':

    polling = PollingDemo()
    polling.looper()  

在此示例中,我尝试通过 Timer 类 timeit() 方法调用 PollingDemo 类的 my_func() 方法,但我收到“NameError: global name 'self' is not defined”错误。如果我们尝试通过 ma​​in 访问该对象,它就可以工作(下一个注释行可以正常工作)。有人可以请为什么这种行为会这样。
提前致谢。

【问题讨论】:

    标签: python


    【解决方案1】:

    不要使用字符串,Timer也接受callables,所以直接传递一个绑定到self的引用,即

    T = Timer(self.my_func)
    

    (只是参考,不要调用它)。

    如果您需要更复杂的设置,请再次将其包装在函数或方法中并传递该方法。

    【讨论】:

    • Ivo 如果您能告诉我当我们将字符串传递给 Timer 类时内部发生了什么,或者任何有关它的参考将不胜感激,那就太好了。 - 谢谢
    • 字符串在其自己的隔离上下文中进行评估(您无法提供本地或全局)。 'self' 将根本不可用。这意味着字符串(可选地与它们的设置字符串)必须是自包含的并定义/引入所有必要的内容。
    【解决方案2】:

    如果您需要传递参数,只需使用 functools 中的 partial:

    import functools
    import timeit
    
    def printme(msg):
        print msg
    
    print "Timing: %f" % timeit.timeit(functools.partial(printme, "Hello world"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      相关资源
      最近更新 更多