获取“未定义全局名称 'foo'"使用 Python 的 timeit [英] Getting "global name 'foo' is not defined" with Python's timeit

查看:31
本文介绍了获取“未定义全局名称 'foo'"使用 Python 的 timeit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道执行一个Python语句需要多少时间,于是上网查了一下,发现标准库提供了一个名为timeit 旨在做到这一点:

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
" % (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

我还是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆