我想使用多进程填充一个大的numpy数组。我已经研究了文档中的concurrent futures示例,但还没有足够的理解来修改用法。
以下是我所需做的简化版本:
输出结果如下:
以下是我所需做的简化版本:
import numpy
import concurrent.futures
squares = numpy.empty((20, 2))
def make_square(i, squares):
print('iteration', i)
squares[i, 0], squares[i, 1] = i, i ** 2
with concurrent.futures.ProcessPoolExecutor(2) as executor:
for i in range(20):
executor.submit(make_square, i, squares)
输出结果如下:
iteration 1
iteration 0
iteration 2
iteration 3
iteration 5
iteration 4
iteration 6
iteration 7
iteration 8
iteration 9
iteration 10
iteration 11
iteration 12
iteration 13
iteration 15
iteration 14
iteration 16
iteration 17
iteration 18
iteration 19
这个很好地展示了函数正在并发运行。但是squares数组仍然为空。
如何正确填充squares数组的语法是什么?
其次,使用.map是否是更好的实现方式?
提前致谢!
2017年8月2日 哇。因为我没有得到任何人解决这个问题,所以我进入了reddit-land。很高兴回到stackoverflow。感谢@ilia w495 nikitin和@donkopotamus。以下是我在reddit上发布的更详细解释这个问题背景的内容。
The posted code is an analogy of what I'm trying to do, which is populating
a numpy array with a relatively simple calculation (dot product) involving
two other arrays. The algorithm depends on a value N which can be anything
from 1 on up, though we won't likely use a value larger than 24.
I'm currently running the algorithm on a distributed computing system and
the N = 20 versions take longer than 10 days to complete. I'm using dozens
of cores to obtain the required memory, but gaining none of the benefits of
multiple CPUs. I've rewritten the code using numba which makes lower N
variants superfast on my own laptop which can't handle the memory
requirements for larger Ns, but alas, our distributed computing environment
is not currently able to install numba. So I'm attempting concurrent.futures
to take advantage of the multiple CPUs in our computing environment in the
hopes of speeding things up.
因此,耗时的不是计算本身,而是1600万次以上的迭代。在上述代码中,初始化的数组为N x 2 ** N,即range(16777216)。
也许通过多进程无法填充数组。
C
部分,其中C
是 CPU 的数量,并在分离的 CPU(进程)上处理每个部分。 然后,连接所有部分,你就会得到想要的结果。 但在某些情况下,这是不适用的。这取决于你的算法。 此外,进程间的数据传输也有其自身的成本。例如,我将尝试使用pymp
实现: https://gist.github.com/w495/6d3cd6a715e3098a3a10a0479d9fbb03使用concurrent.futures
将更容易。 - Ilia w495 Nikitinconcurrent.futures.ProcessPoolExecutor
实现了分区:https://gist.github.com/w495/82f7b21509a69a0d70e18f2e4ddf5ed9 我认为这也可能对你有所帮助。 - Ilia w495 Nikitin