我有一个256x256x256
Numpy 数组,其中每个元素都是一个矩阵。我需要对这些矩阵中的每一个进行一些计算,并且我想使用该multiprocessing
模块来加快速度。
这些计算的结果必须256x256x256
像原来的那样存储在一个数组中,这样原数组中元素处的矩阵的结果就[i,j,k]
必须放在[i,j,k]
新数组的元素中。
为此,我想制作一个可以以伪方式编写的列表,[array[i,j,k], (i, j, k)]
并将其传递给要“多处理”的函数。假设这matrices
是从原始数组中提取的所有矩阵的列表,并且myfunc
是进行计算的函数,代码看起来有点像这样:
import multiprocessing
import numpy as np
from itertools import izip
def myfunc(finput):
# Do some calculations...
...
# ... and return the result and the index:
return (result, finput[1])
# Make indices:
inds = np.rollaxis(np.indices((256, 256, 256)), 0, 4).reshape(-1, 3)
# Make function input from the matrices and the indices:
finput = izip(matrices, inds)
pool = multiprocessing.Pool()
async_results = np.asarray(pool.map_async(myfunc, finput).get(999999))
但是,似乎map_async
实际上是finput
首先创建了这个巨大的列表:我的 CPU 并没有做太多事情,但是内存和交换在几秒钟内就被完全消耗掉了,这显然不是我想要的。
有没有办法将这个巨大的列表传递给多处理函数,而无需先显式创建它?或者你知道解决这个问题的另一种方法吗?
非常感谢!:-)