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尚未運行完畢......威爾這兩種方法之間必然存在性能差異?
使用異步方法的關鍵在於避免等待結果,因爲它們將在以後使用。 –