Python Timeit和"全局名称......未定义"

ced*_*m34 6 python global-variables timeit

我有一个用于代码优化的timit函数的问题.例如,我在文件中编写带参数的函数,让我们调用它myfunctions.py包含:

def func1(X):
    Y = X+1
    return Y
Run Code Online (Sandbox Code Playgroud)

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

import myfunctions
X0 = 1
t = Timer("Y0 = myfunctions.func1(X0)")
print Y0
print t.timeit()
Run Code Online (Sandbox Code Playgroud)

Y0不计算,即使我评论print Y0线错误global name 'myfunctions' is not defined发生.

如果我使用命令指定安装程序

t = Timer("Y0 = myfunctions.func1(X0)","import myfunctions")
Run Code Online (Sandbox Code Playgroud)

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

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

Rom*_*huk 6

你需要setup参数.尝试:

Timer("Y0 = myfunctions.func1(X0)", setup="import myfunctions; X0 = 1")
Run Code Online (Sandbox Code Playgroud)