Python多处理:为什么大的块大小会更慢? [英] Python multiprocessing: why are large chunksizes slower?

查看:59
本文介绍了Python多处理:为什么大的块大小会更慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Python的多处理模块来分析一些代码('job'函数只是对数字进行平方).

I've been profiling some code using Python's multiprocessing module (the 'job' function just squares the number).

data = range(100000000)
n=4
time1 = time.time()
processes = multiprocessing.Pool(processes=n)
results_list = processes.map(func=job, iterable=data, chunksize=10000)
processes.close()
time2 = time.time()
print(time2-time1)
print(results_list[0:10])

我发现奇怪的是,最佳块大小似乎约为1万个元素-这在我的计算机上花费了16秒.如果我将块大小增加到100k或200k,那么它将减慢到20秒.

One thing I found odd is that the optimal chunksize appears to be around 10k elements - this took 16 seconds on my computer. If I increase the chunksize to 100k or 200k, then it slows to 20 seconds.

这种差异是否可能是因为较长列表的酸洗所需的时间更长? 100个元素的块大小需要62秒,我认为这是由于在不同进程之间来回传递块需要额外的时间.

Could this difference be due to the amount of time required for pickling being longer for longer lists? A chunksize of 100 elements takes 62 seconds which I'm assuming is due to the extra time required to pass the chunks back and forth between different processes.

推荐答案

关于最佳块大小:

  1. 拥有大量的小块将允许4个不同的工人更有效地分配负载,因此希望有较小的块.
  2. 另一方面,每次需要处理新块时,与进程相关的上下文更改都会增加开销,因此上下文更改的数量较少,因此需要较少的块.

由于这两个规则都需要不同的方法,所以中间的一点是要走的路,类似于供求图.

As both rules want different aproaches, a point in the middle is the way to go, similar to a supply-demand chart.

这篇关于Python多处理:为什么大的块大小会更慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆