Python Timeit 和“全局名称...未定义”
我对代码优化的 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名称“myfunctions”未定义
发生了。
如果我现在使用命令指定设置
t = Timer("Y0 = myfunctions.func1(X0)","import myfunctions")
,则会发生错误全局名称“X0”未定义
。
有人知道如何解决这个问题吗?非常感谢。
I have a problem with timit function for code optimization. For example, I writing functions with parameters in a file, let's call it myfunctions.py
containing :
def func1(X):
Y = X+1
return Y
and I test this function in a second file test.py
where I call the timer function to test code performance (in obviously more complex problems!) containing :
import myfunctions
X0 = 1
t = Timer("Y0 = myfunctions.func1(X0)")
print Y0
print t.timeit()
The Y0
is not calculated, and even if I comment print Y0
line the error global name 'myfunctions' is not defined
occured.
If I specify the setup with the command
t = Timer("Y0 = myfunctions.func1(X0)","import myfunctions")
now the error global name 'X0' is not defined
occurred.
Is someone know how to solve this ? Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
setup
参数。尝试:You need
setup
parameter. Try:Y0
未定义的原因是您已在字符串中定义它,但在执行开始的解析时,尚未对字符串进行求值以使变量生效。因此,在脚本顶部的某个位置放置一个Y0 = 0
来预先定义它。所有外部函数和变量都必须使用其
setup
参数提供给Timer
。因此,您需要"import myfunctions; X0 = 1"
作为设置参数。这将起作用:
看看我如何使用
"X0 = %i" % (X0,)
传入外部 X0 变量的实际值。您可能想知道的另一件事是,如果您的主文件中有任何想要在
timeit
中使用的函数,您可以通过传递timeit
来识别它们>from __main__ import * 作为第二个参数。如果您希望 timeit 能够修改变量,那么您不应该向它们传递字符串。您可以更方便地将可调用对象传递给它。您应该传递一个可更改所需变量的可调用函数。那么您就不需要
设置
了。看:如您所见,我将
print Y0
afterprint t.timeit()
放在执行之前,因为在执行之前您无法更改其值!The reason for
Y0
being undefined is that you have defined that in a string, but at parse time in the beginning of the execution the string is not evaluated yet to bring the variable into life. So put anY0 = 0
somewhere at the top of your script to have it defined beforehand.All external functions and variables must be given to
Timer
using itssetup
argument. So you need"import myfunctions; X0 = 1"
as the setup parameter.This will work:
Look how I used
"X0 = %i" % (X0,)
to pass in the real value of the external X0 variable.Another thing you might want to know is that if there are any functions in your main file that you want to use in
timeit
, you can maketimeit
recognize them by passingfrom __main__ import *
as the second argument.If you want
timeit
to be able to modify your variables, then you shouldn't pass strings to them. More conveniently you can pass callables to it. You should pass a callable that changes your desired variable. You don't needsetup
then. Look:As you see, I put
print Y0
afterprint t.timeit()
since before execution you can't have its value changed!