【问题标题】:Am I using python's apply_async correctly?我是否正确使用了 python 的 apply_async?
【发布时间】:2016-08-01 15:12:28
【问题描述】:

这是我第一次尝试在 Python 中使用多处理。我正在尝试在我的数据帧df 上按行并行化我的函数fun。回调函数只是将结果附加到一个空列表中,稍后我将对其进行排序。

这是使用apply_async 的正确方法吗?非常感谢。

import multiprocessing as mp

function_results = []
async_results = []

p = mp.Pool() # by default should use number of processors

for row in df.iterrows():
    r = p.apply_async(fun, (row,), callback=function_results.extend)
    async_results.append(r)

for r in async_results:
    r.wait()

p.close()
p.join()

【问题讨论】:

    标签: python python-2.7 multiprocessing python-multiprocessing


    【解决方案1】:

    看起来使用mapimap_unordered(取决于您是否需要订购结果)会更好地满足您的需求

    import multiprocessing as mp
    
    #prepare stuff
    
    if __name__=="__main__":
    
        p = mp.Pool()
    
        function_results = list(p.imap_unorderd(fun,df.iterrows())) #unordered
        #function_results = p.map(fun,df.iterrows()) #ordered
    
        p.close()
    

    【讨论】:

    • 感谢您的回复 - 为什么 mapimap 更好?
    • 速度可能有所不同,但我没有测试过。 imap 和 imap_unordered 更快地返回它们的第一个结果,并且您不需要一次将完整的输出保存在内存中 - 如果您只是要对其进行迭代,这可能会很有趣。
    猜你喜欢
    • 2021-10-03
    • 2011-07-14
    • 2014-07-19
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多