2017-06-21 211 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以最小化。性能优势可能来自该优化,但它将取决于每个单元的计算成本。

我建议坚持更可读性,只有在性能是真实关注,以基准和评估结果。