Python timeit problem
Asked Answered
L

2

6

I'm trying to use the timeit module but I don't know how. I have a main:

from Foo import Foo
if __name__ == '__main__':
...
   foo = Foo(arg1, arg2) 
   t = Timer("foo.runAlgorithm()")
   print t.timeit(2)

and my Class Foo has a method named as runAlgorithm()

the error is this:

NameError: global name 'foo' is not defined

What am I doing wrong? Can I take the time from a class method?

Lalise answered 18/10, 2010 at 15:49 Comment(0)
C
16

Instead of using the necessary setup parameter for setting up the timeit environment, you can simply pass the method (or anything that is callable):

t = Timer(foo.runAlgorithm)

From the documentation:

Changed in version 2.6: The stmt and setup parameters can now also take objects that are callable without arguments.

If you need to pass some arguments, you can use function currying with functools.partial, for example:

class C:
    def printargs(self, a, b):
        print a, b

from functools import partial
foo = C()
t = Timer(partial(foo.printargs, 1, 2))
Cootch answered 18/10, 2010 at 15:55 Comment(3)
I think without arguments needs to be highlightedLanyard
Well, if you need to pass arguments, you could simply use a small wrapper function.Gobble
@SilentGhost: Edited to include an example with arguments.Cootch
L
2

as docs example show you need to pass setup statements:

t = Timer("foo.runAlgorithm()", 'from __main__ import foo')
Lanyard answered 18/10, 2010 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.