How to use time.clock() function in python

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Jan 23 01:18:44 CET 2007


On Mon, 22 Jan 2007 15:32:58 -0800, samuel.y.l.cheung wrote:

>   File "/usr/lib/python2.4/timeit.py", line 188, in repeat
>     t = self.timeit(number)
>   File "/usr/lib/python2.4/timeit.py", line 161, in timeit
>     timing = self.inner(it, self.timer)
>   File "<timeit-src>", line 6, in inner
> NameError: global name 'func1' is not defined
> 
> I don't understand why i can't find 'func1', when I call the function
> 'func1' directly, it works.
> but why when I call it within 'timeit', it can't find it?

Because the code in timeit is running in a different namespace. You have
to import your function first. That's what the setup parameter is used for.

Here's the hard way:

t = timeit.Timer("func1()", """def func1():
    #do something here
    return result
""")


Here's the easy way:

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



-- 
Steven D'Aprano 




More information about the Python-list mailing list