我正在编写一个分子动力学代码,需要使用 3 个函数(即 Compute2BodyForce、Compute3BodyForce 和 ComputeOtherForce)计算 3 种不同类型的力。由于这些函数是相互独立的,并且我想在 3 个不同的内核上分别计算每个函数,因此正确的方法如下:
funList = {@Compute2BodyForce,@Compute3BodyForce,@ComputeOtherForce};
dataList = {data1,data2,data3}; %# or pass file names
parfor i=1:length(funList)
%# call the function
funList{i}(dataList{i});
end
其次,如何将结果合并起来,即得到TotalForce = 2BodyForce + 3BodyForce + OtherForce?
最佳答案
你走在正确的道路上。但是,据我所知,您不能在 parfor 中使用匿名函数(如果我错了或者这仅在早期版本中是正确的,我深表歉意)。此外,您还需要一行来打开 matlab 池并通知工作节点您打算在并行部分中使用什么。这就是我开始解决这个问题的方法:
fileDep = {'Compute2BodyForce',...
'Compute3BodyForce',...
'ComputeOtherForce'};
num_procs = 3;
matlabpool('open','Mycluster',num_procs,'FileDependencies',fileDep);
parfor iter = 1:3
% iter is passed to the functions so the functions can return NaNs when we don't want computation done
body_2_dummy{iter} = Compute2BodyForce(data,iter); %assuming data is a variable here, maybe a struct that gets parsed inside the functions
body_3_dummy{iter} = Compute3BodyForce(data,iter);
other_dummy{iter} = ComputeOtherForce(data,iter);
end
% resolve and sum up here
total_force = body_2_dummy{1} + body_3_dummy{2} + other_dummy{3};
请注意,除了 body_2_dummy{1}、body_3_dummy{2} 和 other_dummy{3} 之外,这些函数的值应返回 NaN。这解决了 Matlab 中令人沮丧的事情。大多数语言的典型编码方式如下:
parfor iter = 1:3
if iter == 1
body_2_dummy = Compute2Body(data);
end
% more ifs for the other forces
end
在这里,我们有责任确保 body_2_dummy 具有明确的值。但在 Matlab 中,这个责任落在解释器身上,并且它不允许这样做,因为它认为 body_2_dummy 取决于执行顺序。
我希望这能让您走上正确的道路。如果有任何其他问题,请随时回来。
此外,作为一般建议,优化函数并尝试降低其成本通常比并行化函数要容易得多。您是否花时间研究过 Matlab 分析器中的力函数?
--安德鲁
后续编辑:
匿名函数是当你做这样的事情时:
spam = @(x) x + 2;
spam(2)
ans = 4
这里,spam是一个匿名函数。您可以通过传递函数句柄(@spam)将函数传递给另一个函数。
我使用并行计算工具箱的经验主要是与 Sbiotoolbox 结合使用。在此工具箱中,生物模型是对象,可以通过基于旧版本 Matlab 句柄图形的句柄引用进行传递。但问题是句柄与模型分离,并且发生了一系列相当令人困惑的错误。因此,在使用 Matlab 的并行功能时,我避免使用句柄进行所有引用。
然而,我必须承认,我还没有测试匿名函数是否可用,因为有一些关于本地与远程 Matlab 工作人员的进一步细节可以给出严格的答案。目前我无法轻松访问远程 Matlab 集群,因此必须将其放在项目列表中。
Matlab profiler 是 Matlab 附带的工具。它允许您放入一个函数并测量每行代码所花费的时间,以便您可以突出显示是否需要重构代码以加快速度。它特别擅长查找错误,例如数组在循环中改变大小,这些错误会消耗 Matlab 的性能。
我鼓励您在 Matlab 帮助中搜索“profiler”。该文档非常好,并且比我放在这里的任何内容都完整得多。
祝你好运。
关于function - MATLAB 上的并行编程可同时执行 3 个不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6248439/