views:

2698

answers:

2

I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called timeit that purports to do exactly that:

import timeit

def foo():
    # ... contains code I want to time ...

def dotime():
    t = timeit.Timer("foo()")
    time = t.timeit(1)
    print "took %fs\n" % (time,)

dotime()

However, this produces an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in dotime
  File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
NameError: global name 'foo' is not defined

I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?

+8  A: 

have you tried making this line:

t = timeit.Timer("foo()")

This:

t = timeit.Timer("foo()", "from __main__ import foo")

Check out the link you provided at the very bottom.

To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:

I just tested it on my machine and it worked with the changes.

Paolo Bergantino
It works! However, this is a pretty stupid interface design if I have to both supply the command I wish to time as a string and to import the __main__ module for it to work.
Kyle Cronin
I've just started dabbling with Python as well and I can't say I disagree. :)
Paolo Bergantino
Python namespacing is utter madness to me. I assume that it makes sense to a certain sort of mind, but that sort of mind isn't one I happen to posess. Thank $DEITY for Ruby, in my case.
womble
womble, this is a wart, not a general python namespace problem. Main thread: http://writeonly.wordpress.com/2008/09/12/using-python-timeit-to-time-functions/ has links to other discussions about this.
Gregg Lind
+1  A: 
t = timeit.Timer("foo()", "from __main__ import foo")

Since timeit doesn't have your stuff in scope.

dwc