【发布时间】:2011-09-05 10:05:03
【问题描述】:
我有一个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:我的 CPU 并没有做太多事情,但是内存和交换在几秒钟内就被完全消耗掉了,这显然不是什么我要。
有没有办法将这个巨大的列表传递给一个多处理函数,而无需先显式创建它? 或者你知道解决这个问题的另一种方法吗?
非常感谢! :-)
【问题讨论】:
-
由于您在
map_async()上使用get(),您可能不想要异步 操作,而应该使用Pool.map()。 -
也许我没有正确理解这个问题,但是你考虑过 imap 还是 imap_unordered?
标签: python multiprocessing itertools