module timeit and variable scope

Fortepianissimo fortepianissimo at gmail.com
Mon Aug 2 16:44:38 EDT 2004


On Mon, 2 Aug 2004 16:30:44 -0400, brianc at temple.edu <brianc at temple.edu> wrote:
> >2. How do I introduce a variable into the timeit.Timer? For
> example I
> >have a class Foo:

> >class Foo:
> >  def __init__ (self):
> >    # the following line didn't work because the scope is not
> >    #   the calling function
> >    # self._timer = timeit.Timer(stmt='self.run(bar)')
> >    pass
> >
> >  def someMethod (self, bar):
> >    print bar
> >
> >  def run (self, bar):
> >    # call self.someMethod(bar) and record time using
> >    #   self._timer
> >    pass
> >
> Just create an instance in the setup portion of the Timer.
> t=timeit.Timer('foo.run()','from __main__ import Foo; foo=Foo()')
> To just test __init__ of your class:
> t=timeit.Timer('Foo()','from __main__ import Foo')
> 
> Setup only runs once.

But this will create a new instance inside the timer. Instead, I want
to use an instance that is created *before* the timer is initialized.
Something like this:


--- CUT HERE ---
import timeit


class Foo:
    def __init__ (self):
        # won't work cuz self is alien to self.timer
        self.timer = timeit.Timer(stmt = 'f.aMethod()', setup = 'f = self')

    def aMethod (self):
        for i in range(10000):
            i *= 2

    def run (self):
        self.timer.timeit()
        self.timer.print_exc()


f = Foo()
f.run()
--- CUT HERE ---

Any other suggestion? Thank you.



More information about the Python-list mailing list