python并行遍历_如何并行化一个简单的Python循环?

并行化此代码的最简单方法是什么?

我真的很喜欢concurrent.futures这一点,在Python3提供自3.2版本 -并通过反向移植到2.6和2.7上的PyPI。

您可以使用线程或进程并使用完全相同的接口。

把它放在一个文件中 - futuretest.py:import concurrent.futuresimport time, random               # add some random sleep timeoffset = 2                        # you don't supply these sodef calc_stuff(parameter=None):   # these are examples.

sleep_time = random.choice([0, 1, 2, 3, 4, 5])

time.sleep(sleep_time)

return parameter / 2, sleep_time, parameter * parameterdef procedure(j):                 # just factoring out the

parameter = j * offset        # procedure

# call the calculation

return calc_stuff(parameter=parameter)def main():

output1 = list()

output2 = list()

output3 = list()

start = time.time()           # let's see how long this takes

# we can swap out ProcessPoolExecutor for ThreadPoolExecutor

with concurrent.futures.ProcessPoolExecutor() as executor:

for out1, out2, out3 in executor.map(procedure, range(0, 10)):

# put results into correct output list

output1.append(out1)

output2.append(out2)

output3.append(out3)

finish = time.time()

# these kinds of format strings are only available on Python 3.6:

# time to upgrade!

print(f'original inputs: {repr(output1)}')

print(f'total time to execute {sum(output2)} = sum({repr(output2)})')

print(f'time saved by parallelizing: {sum(output2) - (finish-start)}')

print(f'returned in order given: {repr(output3)}')if __name__ == '__main__':

main()

这是输出:$ python3 -m futuretest

original inputs: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]total time to execute 33 = sum([0, 3, 3, 4, 3, 5, 1, 5, 5, 4])time saved by parallellizing: 27.68999981880188returned in order given: [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]

多线程

现在更改ProcessPoolExecutor为ThreadPoolExecutor,然后再次运行该模块:$ python3 -m futuretest

original inputs: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]total time to execute 19 = sum([0, 2, 3, 5, 2, 0, 0, 3, 3, 1])time saved by parallellizing: 13.992000102996826returned in order given: [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]

现在你已经完成了多线程和多处理!

关于性能的注意事项并一起使用。

采样太小,无法比较结果。

但是,我怀疑多线程通常比多处理更快,特别是在Windows上,因为Windows不支持分配,所以每个新进程都需要花时间启动。在Linux或Mac上,他们可能会更接近。

您可以在多个进程中嵌套多个线程,但建议不要使用多个线程来分离多个进程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值