python - multiprocessing.Pool() 比仅使用普通函数慢

标签 python performance multiprocessing pool

(这个问题是关于如何让 multiprocessing.Pool() 运行代码更快。我终于解决了,最终解决方案可以在帖子底部找到。)

原问题:

我正在尝试使用 Python 将一个单词与列表中的许多其他单词进行比较,并检索最相似的列表。为此,我使用了 difflib.get_close_matches 函数。我在使用 Python 2.6.5 的相对较新且功能强大的 Windows 7 笔记本电脑上。

我想要的是加快比较过程,因为我的单词比较列表很长,我必须多次重复比较过程。当我听说多处理模块时,如果比较可以分解为工作任务并同时运行(从而利用机器功率来换取更快的速度),我的比较任务将更快地完成,这似乎是合乎逻辑的。

然而,即使尝试了许多不同的方法,并使用了文档中显示和论坛帖子中建议的方法,Pool 方法似乎非常慢,比仅在整个列表上运行原始 get_close_matches 函数慢得多一次。我想帮助理解为什么 Pool() 如此缓慢以及我是否正确使用它。我只使用这个字符串比较场景作为例子,因为这是我能想到的最近的例子,我无法理解或让多处理工作而不是反对我。下面只是来自 difflib 场景的示例代码,显示了普通方法和 Pooled 方法之间的时间差异:

from multiprocessing import Pool
import random, time, difflib

# constants
wordlist = ["".join([random.choice([letter for letter in "abcdefghijklmnopqersty"]) for lengthofword in xrange(5)]) for nrofwords in xrange(1000000)]
mainword = "hello"

# comparison function
def findclosematch(subwordlist):
    matches = difflib.get_close_matches(mainword,subwordlist,len(subwordlist),0.7)
    if matches <> []:
        return matches

# pool
print "pool method"
if __name__ == '__main__':
    pool = Pool(processes=3)
    t=time.time()
    result = pool.map_async(findclosematch, wordlist, chunksize=100)
    #do something with result
    for r in result.get():
        pass
    print time.time()-t

# normal
print "normal method"
t=time.time()
# run function
result = findclosematch(wordlist)
# do something with results
for r in result:
    pass
print time.time()-t

要查找的单词是“hello”,查找接近匹配的单词列表是 100 万个长列表,其中包含 5 个随机连接的字符(仅用于说明目的)。我使用 3 个处理器内核和块大小为 100 的 map 函数(我认为每个 worker 要处理的列表项??)(我也尝试了 1000 和 10 000 的块大小,但没有真正的区别)。请注意,在这两种方法中,我都在调用我的函数之前启动计时器,并在循环结果后立即结束它。正如您在下面看到的,计时结果显然有利于原始的非池方法:
>>> 
pool method
37.1690001488 seconds
normal method
10.5329999924 seconds
>>> 

Pool 方法几乎比原始方法慢 4 倍。我在这里遗漏了什么,或者可能对池化/多处理的工作方式有误解?我确实怀疑这里的部分问题可能是 map 函数返回 None ,因此将数千个不必要的项目添加到结果列表中,即使我只希望将实际匹配项返回到结果并在函数中这样写。据我了解,这就是 map 的工作原理。我听说过一些其他功能,例如 filter 只收集非 False 结果,但我认为 multiprocessing/Pool 不支持 filter 方法。除了多处理模块中的 map/imap 之外,还有其他函数可以帮助我只返回函数返回的内容吗?根据我的理解,Apply 函数更多地用于提供多个参数。

我知道还有 imap 功能,我尝试过但没有任何时间改进。原因与我在理解 itertools 模块的伟大之处时遇到问题的原因相同,据说“闪电般快”,我注意到调用该函数是正确的,但根据我的经验和我读过的内容因为调用该函数实际上并不做任何计算,所以当需要迭代结果以收集和分析它们时(没有这些,调用 cuntion 就没有意义)它花费的时间与 a 一样多,有时甚至更多只需使用函数的普通版本即可。但我想那是另一个帖子。

无论如何,很高兴看到有人能在这里插入我朝着正确的方向前进,并且非常感谢您对此的任何帮助。我对理解多处理一般比让这个例子工作更感兴趣,尽管一些示例解决方案代码建议有助于我的理解。

答案:

似乎减速与其他进程的缓慢启动时间有关。我无法让 .Pool() 函数足够快。我最终加快速度的解决方案是手动拆分工作负载列表,使用多个 .Process() 而不是 .Pool(),并在队列中返回解决方案。但我想知道最关键的变化是否可能是根据要查找的主要词而不是要比较的词来分配工作量,也许是因为 difflib 搜索功能已经如此之快。这是同时运行 5 个进程的新代码,结果比运行简单代码快 10 倍(6 秒对 55 秒)。除了 difflib 已经有多快之外,对于快速模糊查找非常有用。
from multiprocessing import Process, Queue
import difflib, random, time

def f2(wordlist, mainwordlist, q):
    for mainword in mainwordlist:
        matches = difflib.get_close_matches(mainword,wordlist,len(wordlist),0.7)
        q.put(matches)

if __name__ == '__main__':

    # constants (for 50 input words, find closest match in list of 100 000 comparison words)
    q = Queue()
    wordlist = ["".join([random.choice([letter for letter in "abcdefghijklmnopqersty"]) for lengthofword in xrange(5)]) for nrofwords in xrange(100000)]
    mainword = "hello"
    mainwordlist = [mainword for each in xrange(50)]

    # normal approach
    t = time.time()
    for mainword in mainwordlist:
        matches = difflib.get_close_matches(mainword,wordlist,len(wordlist),0.7)
        q.put(matches)
    print time.time()-t

    # split work into 5 or 10 processes
    processes = 5
    def splitlist(inlist, chunksize):
        return [inlist[x:x+chunksize] for x in xrange(0, len(inlist), chunksize)]
    print len(mainwordlist)/processes
    mainwordlistsplitted = splitlist(mainwordlist, len(mainwordlist)/processes)
    print "list ready"

    t = time.time()
    for submainwordlist in mainwordlistsplitted:
        print "sub"
        p = Process(target=f2, args=(wordlist,submainwordlist,q,))
        p.Daemon = True
        p.start()
    for submainwordlist in mainwordlistsplitted:
        p.join()
    print time.time()-t
    while True:
        print q.get()

最佳答案

我最好的猜测是进程间通信 (IPC) 开销。在单进程实例中,单进程有单词列表。当委托(delegate)给各种其他进程时,主进程需要不断地将列表的部分穿梭到其他进程。

因此,更好的方法可能是分拆 n 个进程,每个进程负责加载/生成列表的 1/n 段并检查单词是否在列表的该部分中。

不过,我不确定如何使用 Python 的多处理库来做到这一点。

关于python - multiprocessing.Pool() 比仅使用普通函数慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20727375/

相关文章:

python - 在查询中链接条件时是否应该选择特定的顺序?

python - PyQt:如何从用户那里获取大量文件名?

r - 如何检查一个向量是否是斐波那契数列

python - 煎饼排序中最短翻转序列的计数

python - 在 Python 中绑定(bind)信号处理程序时,<Finalize object, dead> 中没有属性 '_popen'“

javascript - 将变量从 python 传递到 javascript

python : Splitting multidimensional lists

php - set_time_limit 不起作用

performance - 是否可以使用 ETW(Windows 事件跟踪)来收集内存统计信息?

python - keras.backend.clear_session() 是删除进程中的 session 还是全局的?