Skip to main content
 首页 » 编程设计

python multiprocessing starmap vs apply_async,哪个更快

2025年02月15日21lexus

假设我有这两种方法来完成相同的任务:

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 会立即返回,但是,如果 func 尚未完成运行,x.get() 可能仍会阻塞主线程……这两种方法之间是否必然存在性能差异?

请您参考如下方法:

在幕后,starmap 所做的几乎与您在第一种方法中所做的一样。它只是一个方便的包装器。提供 map 函数系列是为了符合许多开发人员习惯的函数式编程范例。

它们提供了一些很好的功能,例如将可迭代对象分成 block 以最小化 IPC。这种优化可能会带来性能优势,但这取决于每个元素的计算成本。

我建议坚持使用更具可读性的内容,并且只有在性能是真正问题时,才对结果进行基准测试和评估。