1 回答

TA貢獻1843條經驗 獲得超7個贊
下面是一個示例,說明如何將 multiprocessing 與一個簡單函數一起使用,該函數接受兩個參數并返回一個包含兩個數字的元組,以及一個您要在其上進行計算的參數空間:
from itertools import product
from multiprocessing import Pool
import numpy as np
def f(a, b):
c = a + b
d = a * b
return (c, d)
a_vals = [1, 2, 3, 4, 5, 6]
b_vals = [10, 11, 12, 13, 14, 15, 16, 17]
na = len(a_vals)
nb = len(b_vals)
p = Pool(8) # <== maximum number of simultaneous worker processes
answers = np.array(p.starmap(f, product(a_vals, b_vals))).reshape(na, nb, 2)
c_vals = answers[:,:,0]
d_vals = answers[:,:,1]
這給出了以下內容:
>>> c_vals
array([[11, 12, 13, 14, 15, 16, 17, 18],
[12, 13, 14, 15, 16, 17, 18, 19],
[13, 14, 15, 16, 17, 18, 19, 20],
[14, 15, 16, 17, 18, 19, 20, 21],
[15, 16, 17, 18, 19, 20, 21, 22],
[16, 17, 18, 19, 20, 21, 22, 23]])
>>> d_vals
array([[ 10, 11, 12, 13, 14, 15, 16, 17],
[ 20, 22, 24, 26, 28, 30, 32, 34],
[ 30, 33, 36, 39, 42, 45, 48, 51],
[ 40, 44, 48, 52, 56, 60, 64, 68],
[ 50, 55, 60, 65, 70, 75, 80, 85],
[ 60, 66, 72, 78, 84, 90, 96, 102]])
返回p.starmap一個二元組列表,然后從中提取 c 和 d 值。
這假定您將在取回所有結果后在主程序中執(zhí)行文件 I/O。
附錄:
如果p.starmap不可用(Python 2),那么您可以更改函數以采用單個輸入(2 元素元組):
def f(inputs):
a, b = inputs
# ... etc as before ...
然后在上面的代碼中使用p.map代替。p.starmap
如果不方便更改函數(例如它也從其他地方調用),那么您當然可以編寫一個包裝函數:
def f_wrap(inputs):
a, b = inputs
return f(a, b)
并改為調用它。
添加回答
舉報