2012-01-04 135 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()因爲在執行之前,你不能有它的價值變了!