草庐IT

Python Timeit 和 “global name ... is not defined”

coder 2023-08-26 原文

我对用于代码优化的 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

有人知道怎么解决吗?非常感谢。

最佳答案

您需要设置参数。尝试:

Timer("Y0 = myfunctions.func1(X0)", setup="import myfunctions; X0 = 1")

关于Python Timeit 和 “global name ... is not defined”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8727108/

有关Python Timeit 和 “global name ... is not defined”的更多相关文章

随机推荐