我用这个例子测试Python中的多处理模块。它计算语料库中每个单词的长度。在from multiprocessing import Pool
def open_file(file):
with open(file) as f:
f = f.read()
return f
def split_words(file):
f = open_file(file)
return [[len(i), i] for i in f.split()]
def split_mult(file):
#uses the multiprocessing module
pool = Pool(processes = 4)
work = pool.apply_async(split_words, [file])
return work.get()
print split_words("random.txt") - about 90seconds for a 110K file
print split_mult("random.txt") - about 90seconds for a 110K file
*split_mult*函数使用多处理,*split_words*不使用。我的印象是,我会看到使用多处理模块更快的处理时间,但在运行时几乎没有差别。每个函数我都运行了大约5次。我有什么遗漏吗?在
更新:
我重新编写了代码,对多处理有了更好的理解,并且能够将处理时间缩短到大约12秒!这是一个快速而肮脏的代码,但希望对其他试图理解这个概念的人有帮助-https://github.com/surajkapoor/MultiProcessing-Test/blob/master/multi.py