2012-03-22 29 views
4

我有一個非常CPU密集型功能:並行運行的許多功能,並收集所有結果以列表

def entity_intersections(ent, collidable): 
    intersections = [] 

    for line1, line2 in product(ent.shape, collidable.shape): 

     pair_intersections = find_intersections(line1 + ent.position, ent.velocity, ent.acceleration, line2 + collidable.position, collidable.velocity, collidable.acceleration, ent, collidable) 
     intersections.extend(pair_intersections) 

    return intersections 

我要讓所有的呼叫並行find_intersections運行,讓他們執行更快,同時仍然收集所有結果(一旦所有執行完成)。考慮到find_intersectionspure function,什麼庫會允許我這樣做?

如何生成這些並行執行以及收集結果的例子將不勝感激。

+0

你的研究表明什麼是一個合適的Python庫? – Marcin 2012-03-22 15:51:55

+0

@Marcin對於性能增強,有一個非常大的選擇:幾個並行處理庫之一(包括2個python內置庫),重新編譯爲協程,Cython等。並行處理不是我的強項...... – Darthfett 2012-03-22 21:33:51

+0

是的,有很多 - 爲什麼不讀一些文件,然後問你什麼時候不能決定幾個好的候選人之間的問題。 – Marcin 2012-03-22 21:35:08

回答

8

最簡單的方法是使用multiprocessing模塊:

class FindIntersectionsWrapper(object): 
    def __init__(self, ent, collidable): 
     self.ent = ent 
     self.collidable = collidable 
    def __call__(self, dims): 
     line1, line2 = dims 
     return find_intersections(
      line1 + self.ent.position, self.ent.velocity, 
      self.ent.acceleration, line2 + self.collidable.position, 
      self.collidable.velocity, self.collidable.acceleration, 
      self.ent, self.collidable) 

def entity_intersections(ent, collidable): 
    find_inter = FindIntersectionsWrapper(ent, collidable) 
    pool = multiprocessing.Pool() 
    return pool.map(find_inter, product(ent.shape, collidable.shape)) 

的幫手功能find_intersections_wrapper()是必要的因爲Pool.map()需要一個帶有單個參數的函數。

您可能希望將創建的poolentity_intersections()中移出,以使生成進程池的開銷只有一次。

編輯:使用類而不是閉包,因爲傳遞給Pool.map()的可調用函數必須在Windows上可供選擇。

+0

''pool.map'對find_intersections裏面的'wrapper'不滿意,所以我在'entity_intersections'裏面生成了'find_intersections'的參數列表,並且用這種方式映射它們。謝謝! :) – Darthfett 2012-03-22 21:19:48

+0

@Darthfett:顯然我無法輕鬆測試這段代碼。我想了解究竟是什麼問題。你在Windows上嗎? – 2012-03-22 21:22:11

+0

是的,我在Windows上。該問題與[此處](http://stackoverflow.com/q/3288595/936083)幾乎相同。 – Darthfett 2012-03-22 21:26:18

0
+1

由於GIL,線程並不能真正增加CPython的CPU利用率。 – agf 2012-03-22 15:56:49

+2

@agf:只要您使用CPython,並且不會將大部分時間花在釋放GIL的函數內,如NumPy數組操作,則這是真實的。我認爲這裏更相關的反對意見是,你從概念上不想在這裏使用線程,因爲'find_intersections()'是一個純函數。 – 2012-03-22 16:00:37

相關問題