python加快速度的模块_使用Python中的多处理模块提高速度

我用这个例子测试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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值