Getting "global name 'foo' is not defined" with Python's timeit
Asked Answered
P

5

106

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?

Prana answered 15/2, 2009 at 23:15 Comment(0)
A
102

Change this line:

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

To 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.

Atcliffe answered 15/2, 2009 at 23:18 Comment(9)
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.Prana
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.Buskin
womble, this is a wart, not a general python namespace problem. Main thread: writeonly.wordpress.com/2008/09/12/… has links to other discussions about this.Pelaga
@Gregg The link is no longer accessible (error 404). What was in that discussion?Footboard
ovgovolin: looks fine to me! writeonly.wordpress.com/2008/09/12/… with links: mail.python.org/pipermail/python-list/2006-November/412340.html and mail.python.org/pipermail/python-list/2006-November/412341.htmlPelaga
ov, those were outdated. now repaired: mail.python.org/pipermail/python-list/2006-November/463664.htmlPelaga
@Gregg Thanks! Please, the next time put @ before the name (ovgolovin or others) when reply. Otherwise the user is not notified (e.g. I wasn't notified when you made the replies in this thread).Footboard
those links are all deadWimer
For Python 3, use the solution by @user2314737 t = timeit.Timer("foo()", globals=globals()) Kelleekelleher
Z
46

With Python 3, you can use globals=globals()

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

From the documentation:

Another option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports

Zincography answered 5/9, 2017 at 12:51 Comment(2)
Works for Python 3 only. globals not a parameter for Python 2's timeitReactant
I had to merge globals and locals like this: imports_and_vars=globals(); imports_and_vars.update(locals()) then pass it like t = timeit.Timer("foo()", globals=imports_and_vars)Goidelic
L
22

You can try this hack:

import timeit

def foo():
    print 'bar'

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

import __builtin__
__builtin__.__dict__.update(locals())

dotime()
Libelee answered 22/3, 2011 at 11:16 Comment(5)
This hack is great if you'd otherwise need complex setup code.Kop
Better than the startup code alternative given in other replies (i.e. better than t = timeit.Timer("foo()", "from __main__ import foo")). Specially if you want to test several different functions, it will save a lot of typing!Couture
I've got about 20 imports, so passing them as an argument gets messy quick. This hack is awesome!Ormandy
Great! On python3 however you need import builtins and 'builtins.__dict__.update(locals())'Profane
Can you time multiple functions in the Time() function?Vincenza
R
8
t = timeit.Timer("foo()", "from __main__ import foo")

Since timeit doesn't have your stuff in scope.

Rascality answered 15/2, 2009 at 23:22 Comment(0)
O
0

add into your setup "import thisfile; "

then when you call the setup function myfunc() use "thisfile.myfunc()"

eg "thisfile.py"

def myfunc():

 return 5

def testable(par):

 pass



t=timeit.timeit(stmt="testable(v)",setup="import thisfile; v=thisfile.myfunc();").repeat(10)

print( t )
Octroi answered 1/6, 2017 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.