0
我有一个字符串列表和每个字符串,我正在做一些更改,您可以在wordify()
中看到。现在,为了加快速度,我使用chunked()
将列表分成子列表(子列表的数量是CPU核心的数量 - 1)。这样我得到的列表看起来像[[,,],[,,],[,,],[,,]]
。使用映射的多处理
我尽量做到:
我想要做的每一个上同时这些子表wordify()
,返回子列表作为单独的列表。我想等到所有过程完成,然后将这些子列表加入到一个列表中。下面的方法不起作用。
import multiprocessing
from multiprocessing import Pool
from contextlib import closing
def readFiles():
words = []
with open("somefile.txt") as f:
w = f.readlines()
words = words + w
return words
def chunked(words, num_cpu):
avg = len(words)/float(num_cpu)
out = []
last = 0.0
while last < len(words):
out.append(words[int(last):int(last + avg)])
last += avg
return out
def wordify(chunk,wl):
wl.append([chunk[word].split(",", 1)[0] for word in range(len(chunk))])
return wl
if __name__ == '__main__':
num_cpu = multiprocessing.cpu_count() - 1
words = readFiles()
chunked = chunked(words, num_cpu)
wordlist = []
wordify(words, wordlist) # works
with closing(Pool(processes = num_cpu)) as p:
p.map(wordify, chunked, wordlist) # fails
首先解决给我: 'cPickle.PicklingError:不能咸菜<类型 '功能'>:属性。查找__builtin __功能failed' 解决方案二的作品,但它比做得单线程慢: '单线程:0.423000097275','多线程:0.605999946594' – doc
你不应该指望提升速度,除非正在进行的工作是巨大的。按第一个逗号分割一行是很困难的工作,而且仅仅通过进程间管道来回传送字符串几乎肯定会花费更多的时间。后者并不是真的很昂贵,而是更多的是你用琴弦做的东西非常便宜。 –
这样做的数据量将大幅增加。有没有更有效的方法来做到这一点,因为我绝对没有看到需要在进程间发送字符串而修改子列表。只有在重新加入子列表时才应该来回发送东西。 – doc