我有一個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? –