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 值。
这假定您将在取回所有结果后在主程序中执行文件 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)
并改为调用它。
添加回答
举报