Getting "global name" foo 'undefined "using Python timeit

I am trying to figure out how long it takes to execute a Python instruction, so I looked online and found that the standard library provides a module called timeit that is designed to do just 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 causes 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 quite understand all the problems it has, but I don't know why this snippet doesn't work. Any thoughts?

+70
scope python timeit
Feb 15 '09 at 23:15
source share
5 answers

Change this line:

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

For this:

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

Check the link that you provided at the bottom.

To give the timeit module access to the functions you define, you can pass a configuration parameter that contains the import statement:

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

+77
Feb 15 '09 at 23:18
source share

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() 
+18
Mar 22 '11 at 11:16
source share
 t = timeit.Timer("foo()", "from __main__ import foo") 

Since timeit does not have your data in scope.

+8
Feb 15 '09 at 23:22
source share

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 the current global namespace. It may be more convenient than an individual indication of import.

+1
Sep 05 '17 at 12:51 on
source share

add "import thisfile" to your setting;

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

for example, "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 ) 
0
Jun 01 '17 at 22:45
source share



All Articles