如何将当前对象引用(self)传递给timeit模块的Timer类?

2024-10-01 09:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将当前的对象引用(即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类的_func()方法,但是我得到了“NameError:global name‘self’is not defined”错误。如果我们试图通过main来访问该对象,它就会工作(下一个注释行非常有效)。有人能请你解释一下为什么这种行为。
提前谢谢。在


Tags: 对象fromimportselftimemainmydef
2条回答

如果需要传递参数,只需使用functools中的部分

import functools
import timeit

def printme(msg):
    print msg

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

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

T = Timer(self.my_func)

(只是参考,不要叫它)。在

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

相关问题 更多 >