Namespaces and the timeit module

David M. Cooke cookedm+news at physics.mcmaster.ca
Mon Dec 13 22:27:07 EST 2004


Roy Smith <roy at panix.com> writes:

> I'm playing with the timeit module, and can't figure out how to time a 
> function call.  I tried:
>
> def foo ():
>     x = 4
>     return x
>
> t = timeit.Timer ("foo()")
> print t.timeit()
>
> and quickly figured out that the environment the timed code runs under 
> is not what I expected:
>
> Traceback (most recent call last):
>   File "./d.py", line 10, in ?
>     print t.timeit()
>   File "/usr/local/lib/python2.3/timeit.py", line 158, in timeit
>     return self.inner(it, self.timer)
>   File "<timeit-src>", line 6, in inner
> NameError: global name 'foo' is not defined
>
> In fact, trying to time "print dir()" gets you:
>
> ['_i', '_it', '_t0', '_timer']
>
> It seems kind of surprising that I can't time functions.  Am I just not 
> seeing something obvious?

Like the documentation for Timer? :-)

class Timer([stmt='pass' [, setup='pass'  [, timer=<timer function>]]])

You can't use statements defined elsewhere, you have to define them in
the setup arguments (as a string). Like this:


define_foo = '''
def foo():
    x = 4
    return x
'''

t = timeit.Timer("foo()" setup=define_foo)
print t.timeit()


One common idiom I've seen is to put your definition of foo() in a
module (say x.py), then, from the command line:

$ python -m timeit -s 'from x import foo' 'foo()'

(the -m is for python 2.4 to run the timeit module; use the full path
to timeit.py instead for earlier pythons)

Alternatively, the examples for the timeit module has another way to
time functions defined in a module.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list