【问题标题】:Parallel Programming on MATLAB to execute 3 different functions at the same time在 MATLAB 上进行并行编程以同时执行 3 个不同的函数
【发布时间】:2011-06-06 06:23:15
【问题描述】:

我正在编写一个分子动力学代码,它需要使用 3 个函数计算 3 种不同类型的力,即 Compute2BodyForce、Compute3BodyForce 和 ComputeOtherForce。由于这些函数是相互独立的,我想在 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?

【问题讨论】:

    标签: function matlab parallel-processing


    【解决方案1】:

    你在正确的轨道上。但是,据我所知,您不能在 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 将函数传递给另一个函数。

    我在并行计算工具箱方面的经验主要是与 Sbiotoolbox 结合使用。在这个工具箱中,生物模型是对象,可以通过句柄引用以基于旧版本的 Matlab 句柄图形的方式传递。但问题是句柄与模型分离,并发生了一系列相当混乱的错误。出于这个原因,我在使用 Matlab 的并行功能时避免了所有的句柄引用。

    但我必须承认,我没有测试匿名函数是否可用,因为有一些关于本地和远程 Matlab 工作人员的更多细节可以给出严格的答案。目前我无法轻松访问远程 Matlab 集群,因此必须将其放在项目列表中。

    Matlab profiler 是 Matlab 自带的工具。它允许您输入一个函数并测量每一行代码所花费的时间,以便您可以突出显示是否需要重组代码以更快。它特别擅长发现像数组在循环中改变大小这样会消耗 Matlab 性能的错误。

    我鼓励您在 Matlab 帮助中搜索“profiler”。文档非常好,比我可以放在这里的任何内容都要完整。

    祝你好运。

    【讨论】:

    • 您好安德鲁,非常感谢您的详细回答。请再问几个问题,我的 MATLAB 知识仅限于相当基本的用法。首先什么是匿名函数?其次,什么是 MATLAB 分析器?
    • @jj-yeo 希望编辑有所帮助。很抱歉让他们起床延迟。如果您对分析器或匿名函数还有其他问题,我鼓励您发布另一个问题,以便您可以更多地关注您的问题。编码愉快!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多