使用 Python 的 timeit 获取“ global name‘ foo’is not Definition”

我试图找出执行一条 Python 语句需要多少时间,所以我上网查了一下,发现标准库提供了一个名为 计时的模块,其目的正是为了实现这一点:

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 还是个新手,并且不完全理解它的所有范围问题,但是我不知道为什么这个代码片段不能工作。有什么想法吗?

45488 次浏览

Change this line:

t = timeit.Timer("foo()")

To this:

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

Check out the link you provided at the very bottom.

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.

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

Since timeit doesn't have your stuff in scope.

You can try this hack:

import timeit


def foo():
print 'bar'


def dotime():
t = timeit.Timer("foo()")
time = t.timeit(1)
print "took %fs\n" % (time,)


import __builtin__
__builtin__.__dict__.update(locals())


dotime()

add into your setup "import thisfile; "

then when you call the setup function myfunc() use "thisfile.myfunc()"

eg "thisfile.py"

def myfunc():


return 5


def testable(par):


pass






t=timeit.timeit(stmt="testable(v)",setup="import thisfile; v=thisfile.myfunc();").repeat(10)


print( t )

With Python 3, you can use globals=globals()

t = timeit.Timer("foo()", globals=globals())

From the documentation:

Another option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports