我有一个 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
-list first:我的CPU没有做太多,但是内存和交换在几秒钟内完全耗尽,这显然不是我想要的。
有没有办法将这个庞大的列表传递给多处理函数而无需先显式创建它? 或者你知道另一种解决这个问题的方法吗?
谢谢你! :-)