timing a function with timeit? (newbie problem)

N

news.west.cox.net

Why do I get the exception "global name 'test' is not defined" in this code
(next to last line) and how do I fix it?

import timeit
def test():
x=2+2
t = timeit.Timer('test()')
print t.timeit()
 
C

Chad Netzer

Why do I get the exception "global name 'test' is not defined" in this code
(next to last line) and how do I fix it?

import timeit
def test():
x=2+2
t = timeit.Timer('test()')
print t.timeit()

You need to tell it about test() with the setup argument (by either
defining it directly, or importing it.
0.61572694778442383
0.71046602725982666

This is because globals are at the module scope. The timeit module is
separate from the interactive (ie. '__main__') namespace. The Timer
function compiles your code in the namespace where it is defined, not
where it is called. So, it's 'globals' are the globals in the timeit
module, and thus, it cannot see your test() function as a global.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top