timing a function with timeit? (newbie problem)
cnetzer at sonic.net
Thu Aug 28 03:24:15 CEST 2003
On Wed, 2003-08-27 at 16:45, news.west.cox.net wrote:
> 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():
> 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.
>>> t = timeit.Timer('test()', 'def test(): x = 2+2')
>>> t = timeit.Timer('test()', 'from __main__ import test')
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.
More information about the Python-list