7

我对用于代码优化的 timit 函数有疑问。例如,我在文件中编写带有参数的函数,我们称它为myfunctions.py包含:

def func1(X):
    Y = X+1
    return Y

我在第二个文件中测试这个函数,test.py我在其中调用计时器函数来测试代码性能(显然是更复杂的问题!)包含:

import myfunctions
X0 = 1
t = Timer("Y0 = myfunctions.func1(X0)")
print Y0
print t.timeit()

没有计算Y0,即使我注释print Y0行也会发生错误global name 'myfunctions' is not defined

如果我使用命令指定设置

t = Timer("Y0 = myfunctions.func1(X0)","import myfunctions")

现在发生了错误global name 'X0' is not defined

有人知道如何解决这个问题吗?非常感谢。

4

2 回答 2

6

你需要setup参数。尝试:

Timer("Y0 = myfunctions.func1(X0)", setup="import myfunctions; X0 = 1")
于 2012-01-04T12:49:41.717 回答
4

未定义的原因Y0是您已经在字符串中定义了它,但是在执行开始的解析时,尚未评估字符串以使变量生效。因此Y0 = 0,在脚本顶部放置一个位置以预先定义它。

所有外部函数和变量都必须Timer使用它的setup参数。所以你需要"import myfunctions; X0 = 1"作为设置参数。

这将起作用:

from timeit import Timer
import myfunctions
X0 = 1
Y0 = 0     #Have Y0 defined
t = Timer("Y0 = myfunctions.func1(X0)", "import myfunctions; X0 = %i" % (X0,))
print t.timeit()
print Y0

看看我过去是如何"X0 = %i" % (X0,)传递外部 X0 变量的实际值的。

您可能想知道的另一件事是,如果您想要在主文件中使用任何函数timeit,您可以timeit通过from __main__ import *作为第二个参数传递来识别它们。


如果您希望timeit能够修改变量,则不应将字符串传递给它们。更方便的是,您可以将可调用对象传递给它。您应该传递一个可更改您所需变量的可调用对象。那你就不需要setup了。看:

from timeit import Timer
import myfunctions

def measure_me():
    global Y0    #Make measure_me able to modify Y0
    Y0 = myfunctions.func1(X0)

X0 = 1
Y0 = 0     #Have Y0 defined
t = Timer(measure_me)
print t.timeit()
print Y0

如您所见,我在执行之前放置了它的值print Y0 print t.timeit()因为您不能更改它的值!

于 2012-01-04T16:37:30.630 回答