2012-01-04 143 views
6

我有一个用于代码优化的timit函数的问题。例如,我在文件中写入功能与参数,让我们称之为myfunctions.py包含:Python Timeit和“全局名称...未定义”

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发生的设置。

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

+0

[使用Python的timeit获取“全局名称foo'未定义”的可能重复](https://stackoverflow.com/questions/551797/getting-global-name-foo-is-not-defined-with -python-timeit) – sds 2017-09-20 16:21:15

回答

6

您需要setup参数。尝试:

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

正如我在问题中提到的,这将返回一个错误“全局名称'X0'未定义” – cedm34 2012-01-04 13:42:33

+0

@ cedm34请参阅更新 – 2012-01-04 14:13:54

+1

全局错误已消失。但是这不会创建Y0值。有没有解决方案? – cedm34 2012-01-04 16:31:56

4

被未定义的原因Y0是你定义在一个字符串,但在开始执行分析时字符串不评估尚未使变量的生活。因此,在脚本的顶部放置一个Y0 = 0以便事先定义它。

必须使用setup参数将所有外部函数和变量提供给Timer。所以你需要"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 Y0print t.timeit()因为在执行之前,你不能有它的价值变了!