获取“全局名称‘foo’” 未定义” 使用Python的timeit
我想知道执行一条Python语句需要多少时间,所以我上网查了一下,发现标准库提供了一个名为 timeit 声称正是这样做的:
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 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()
However, this produces 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 fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更改此行:
为此:
查看您在最底部提供的链接。
我刚刚在我的机器上测试了它,并且它可以处理更改。
Change this line:
To this:
Check out the link you provided at the very bottom.
I just tested it on my machine and it worked with the changes.
globals=globals()
对于 Python 3,您可以使用
With Python 3, you can use
globals=globals()
From the documentation:
你可以尝试这个技巧:
You can try this hack:
因为 timeit 的范围内没有你的东西。
Since timeit doesn't have your stuff in scope.
添加到您的设置中“import thisfile;”
然后当您调用设置函数 myfunc() 时使用“thisfile.myfunc()”
例如“thisfile.py”
add into your setup "import thisfile; "
then when you call the setup function myfunc() use "thisfile.myfunc()"
eg "thisfile.py"