开发者

How to pass current object reference(self) to the Timer class of timeit module?

I am trying to pass current object reference i.e. self to the Ti开发者_如何转开发mer class of timeit module but somehow i am not getting it how to do it. I tried to find it in timeit documentation but i could not find it. I have attached my code with this question.

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()  

In this example i have tried to call my_func() method of PollingDemo class through Timer class timeit() method but i am getting "NameError: global name 'self' is not defined" error. if we tried to access that object through main it works (Next commented line works perfectly). Can someone please why is this behavior so.

Thanks in advance.


Don't use a string, Timer also accepts callables, so pass a reference bound to self directly, i.e.

T = Timer(self.my_func)

(just the reference, don't call it).

If you need more complex setup, again wrap it in a function or method and pass that method.


If you need to pass arguments, just use partial from functools:

import functools
import timeit

def printme(msg):
    print msg

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜