两个for循环的多重处理

我正在努力在 python (2.7) 中实现算法以并行化物理问题的计算。在两个变量(假设 a 和 b)上有一个参数空间,我想在上面运行我编写的程序 f(a,b),它返回另外两个变量 c 和 d。

到目前为止,我for在 a 和 b 上使用了两个循环来计算 c 和 d 的两个数组,然后将它们保存为 txt 文档。由于参数空间比较大,每次计算其中的一个点f(a,b)的时间都比较长,如果能把我的8个CPU核全部用于参数空间扫描就好了。

我已经阅读了有关多线程和多处理的信息,似乎多处理就是我正在寻找的东西。你知道这个应用程序的一个很好的代码示例或资源来了解我相当简单的应用程序的多处理基础知识吗?


慕姐4208626
浏览 72回答 1
1回答

蓝山帝景

下面是一个示例,说明如何将 multiprocessing 与一个简单函数一起使用,该函数接受两个参数并返回一个包含两个数字的元组,以及一个您要在其上进行计算的参数空间:from itertools import productfrom multiprocessing import Poolimport numpy as npdef f(a, b):&nbsp; &nbsp; c = a + b&nbsp; &nbsp; d = a * b&nbsp; &nbsp; 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)&nbsp; # <== maximum number of simultaneous worker processesanswers = np.array(p.starmap(f, product(a_vals, b_vals))).reshape(na, nb, 2)c_vals = answers[:,:,0]d_vals = answers[:,:,1]这给出了以下内容:>>> c_valsarray([[11, 12, 13, 14, 15, 16, 17, 18],&nbsp; &nbsp; &nbsp; &nbsp;[12, 13, 14, 15, 16, 17, 18, 19],&nbsp; &nbsp; &nbsp; &nbsp;[13, 14, 15, 16, 17, 18, 19, 20],&nbsp; &nbsp; &nbsp; &nbsp;[14, 15, 16, 17, 18, 19, 20, 21],&nbsp; &nbsp; &nbsp; &nbsp;[15, 16, 17, 18, 19, 20, 21, 22],&nbsp; &nbsp; &nbsp; &nbsp;[16, 17, 18, 19, 20, 21, 22, 23]])>>> d_valsarray([[ 10,&nbsp; 11,&nbsp; 12,&nbsp; 13,&nbsp; 14,&nbsp; 15,&nbsp; 16,&nbsp; 17],&nbsp; &nbsp; &nbsp; &nbsp;[ 20,&nbsp; 22,&nbsp; 24,&nbsp; 26,&nbsp; 28,&nbsp; 30,&nbsp; 32,&nbsp; 34],&nbsp; &nbsp; &nbsp; &nbsp;[ 30,&nbsp; 33,&nbsp; 36,&nbsp; 39,&nbsp; 42,&nbsp; 45,&nbsp; 48,&nbsp; 51],&nbsp; &nbsp; &nbsp; &nbsp;[ 40,&nbsp; 44,&nbsp; 48,&nbsp; 52,&nbsp; 56,&nbsp; 60,&nbsp; 64,&nbsp; 68],&nbsp; &nbsp; &nbsp; &nbsp;[ 50,&nbsp; 55,&nbsp; 60,&nbsp; 65,&nbsp; 70,&nbsp; 75,&nbsp; 80,&nbsp; 85],&nbsp; &nbsp; &nbsp; &nbsp;[ 60,&nbsp; 66,&nbsp; 72,&nbsp; 78,&nbsp; 84,&nbsp; 90,&nbsp; 96, 102]])返回p.starmap一个二元组列表,然后从中提取 c 和 d 值。这假定您将在取回所有结果后在主程序中执行文件 I/O。附录:如果p.starmap不可用(Python 2),那么您可以更改函数以采用单个输入(2 元素元组):def f(inputs):&nbsp; &nbsp; a, b = inputs&nbsp; &nbsp; # ... etc as before ...然后在上面的代码中使用p.map代替。p.starmap如果不方便更改函数(例如它也从其他地方调用),那么您当然可以编写一个包装函数:def f_wrap(inputs):&nbsp; &nbsp; a, b = inputs&nbsp; &nbsp; return f(a, b)并改为调用它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python