2009-09-12 94 views
6

我想在多處理池中的每個進程上運行cProfile.runctx(),以瞭解我的源中多處理瓶頸是什麼。這裏是什麼,我試圖做一個簡單的例子:分析一個python多處理池

from multiprocessing import Pool 
import cProfile 

def square(i): 
    return i*i 

def square_wrapper(i): 
    cProfile.runctx("result = square(i)", 
     globals(), locals(), "file_"+str(i)) 
    # NameError happens here - 'result' is not defined. 
    return result 

if __name__ == "__main__": 
    pool = Pool(8) 
    results = pool.map_async(square_wrapper, range(15)).get(99999) 
    print results 

不幸的是,試圖執行「結果=方(I)」的探查並不在範圍影響「結果」它是從所謂的。我怎樣才能完成我想在這裏做的事情?

回答

6

試試這個:

def square_wrapper(i): 
    result = [None] 
    cProfile.runctx("result[0] = square(i)", globals(), locals(), "file_%d" % i) 
    return result[0] 
+2

+1;工作,但似乎相當hacky。 你能解釋它爲什麼有效嗎? – Fragsworth 2009-09-12 11:13:21

+1

我猜'result = square(i)'只是在cProfile.runctx範圍內創建了一個新的引用,或者在它執行代碼的任何地方創建了一個新的引用,從而保留原有的引用。在runctx之前使用「全局結果」,並在內部使用「global result; result = square(i)」(或「globals()['result'] = square(i)」)。 – 2009-09-12 11:23:53