我有一个256x256x256
Numpy数组,其中每个元素是一个矩阵。我需要对这些矩阵中的每一个做一些计算,并且我想使用multiprocessing
模块来加快速度。结合itertools和多处理?
这些计算的结果必须被存储在一个阵列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没有太多的工作,但内存和交换在几秒钟内完全消耗,这显然不是我想要的。
有没有办法将这个庞大的列表传递给一个多处理函数,而无需先显式创建它? 或者你知道解决这个问题的另一种方法吗?
非常感谢! :-)
由于您在'map_async()'上使用'get()',因此您可能不希望执行* asynchronous *操作,而应该使用'Pool.map()'。 –
也许我不明白这个问题,但你有没有考虑过imap或imap_unordered? –