2017-06-21 76 views
0

假設我有這兩個來完成相同的任務的方法:python multiprocessing starmap vs apply_async,哪個更快?

from multiprocessing import Pool 
pool = Pool(4) 

def func(*args): 
    # do some slow operations 
    return something 

dates = ['2011-01-01', ' 2011-01-02', ... , '2017-01-01'] 
other_args = [1, 2, 3, 'c', 'test', 'pdf')] 
# approach 1: 
res = [pool.apply_async(func, [day] + other_args) for day in dates] 
list_of_results = [x.get() for x in res] 

# approach 2: create an iterable of iterables 
args = [[day] + other_args for day in dates] 
list_of_results = pool.starmap(func, args) 

我馬上意識到apply_async回報,然而,x.get()仍然可能阻塞主線程,如果FUNC尚未運行完畢......威爾這兩種方法之間必然存在性能差異?

+0

使用異步方法的關鍵在於避免等待結果,因爲它們將在以後使用。 –

回答

1

在引擎蓋下,starmap幾乎做了你在第一種方法中所做的。這只是一個便利的包裝。提供的功能系列是爲了符合許多開發人員習慣的功能性編程範例。

它們提供了一些很好的功能,例如將塊中的迭代器拆分爲IPC以最小化。性能優勢可能來自該優化,但它將取決於每個單元的計算成本。

我建議堅持更可讀性,只有在性能是真實關注,以基準和評估結果。

相關問題