获取“未定义全局名称'foo'";用Python的timeit [英] Getting "global name 'foo' is not defined" with Python's timeit
问题描述
我试图找出执行一条Python语句要花费多少时间,所以我上网查看了一下,发现标准库提供了一个名为
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()
但是,这会产生错误:
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
我还是Python的新手,我还不完全了解它的所有作用域问题,但是我不知道为什么此代码段不起作用.有什么想法吗?
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?
推荐答案
更改此行:
t = timeit.Timer("foo()")
对此:
t = timeit.Timer("foo()", "from __main__ import foo")
查看您在底部提供的链接.
Check out the link you provided at the very bottom.
要让timeit模块访问您定义的功能,可以传递一个包含导入语句的设置参数:
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.
这篇关于获取“未定义全局名称'foo'";用Python的timeit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!