我正在尝试利用我的计算机中的多个内核,用python多处理库处理数百万个文件中的文本。下面的代码显示了主函数和辅助函数,这些函数将路径作为输入重运行(1000个或更少),这些单词在路径中的所有文件中出现最多(这些函数没有任何问题,只是作为参考)。在
import multiprocessing as mp
def worker(fileNameList):
'''Takes a file name list and reruns a word frequency map of all the files in a dict'''
vacob=dict()
for fileName in fileNameList:
xmlfile=open(fileName)
tree=html.fromstring(xmlfile.read())
paras=tree.xpath("//title/text()|//headline/text()|//text/p/text()")
docString="".join(paras)
wordList=preprocess_pipeline(docString)
for word in wordList:
if vacob.has_key(word):
vacob[word]=vacob[word]+1
else:
vacob[word]=1
xmlfile.close()
output.put(vacob)
def master(path,n=8):
'''Takes a path as input and returns a vocabulary of(10000 or less) words for all the files in the path'''
vacob=defaultdict(int)
xmlFiles=[f for f in listdir(path) if isfile(join(path,f)) and os.path.splitext(f)[1]=='.xml']
length=len(xmlFiles)
parts=length/n
processes=list()
for i in range(n):
processes.append(mp.Process(target=worker,args=[xmlFiles[i*parts:(i+1)*parts]]))
for i in processes:
i.start()
for i in processes:
i.join()
for j in range(n):
results=output.get()
for word in results:
vacob[word]+=1
vacob=sorted(vacob,key=vacob.get,reverse=True)
if(len(vacob)<10000):
return vacob
else:
return vacob[:10000]
output=mp.Queue()
vocab=master(path)
这应该可以利用我电脑的所有8个核心。但是所有的过程都只共享我的一个核心中央处理器下图显示了文本处理.py脚本只使用一个核心。怎么做我可以让脚本使用所有可用的内核吗?在
当我试着调试打印文件时,每个工人都在处理。它似乎利用了所有的核心。但我还是不明白为什么一个简单的打印声明使用了所有的核心。在
下面是带有调试打印的修改后的代码。在
^{pr2}$以下是htop和控制台的屏幕截图:
目前没有回答
相关问题 更多 >
编程相关推荐