【问题标题】:parallel programming in MATLABMATLAB中的并行编程
【发布时间】:2017-05-19 04:28:36
【问题描述】:

我有一个运行缓慢的 MATLAB 函数,并且我确定了两行计算密集型代码。我还发现这两行代码互不依赖,可以并行化。我想知道并行化这两行代码的最佳方法是什么,比如说我的代码是这样的:

function [y,x] = test1(a)
    y = exp(a);
    x = sin(a);
end

假设a是一个大矩阵,那么如何并行计算y和x。 Parfor 是一种方法,例如:

parfor i = 1:2
    if i == 1
        y = exp(a);
    else
        x = sin(a);
    end
end

我觉得这种方式太天真了,想知道有没有其他方法可以解决这个问题。

【问题讨论】:

    标签: matlab parallel-processing parfor


    【解决方案1】:

    如果您不想使用 parfor,您可以为要在单个 worker 上执行的每个函数创建一个批处理。

    a = 10;
    % starts execution on separate workers
    exp_handle = batch(@exp,1,{a});
    sin_handle = batch(@sin,1,{a});
    
    % waits ultil the first is complete and gets the result
    wait(exp_handle);
    yc = fetchOutputs(exp_handle); % cell
    
    % waits until the second is complete and gets the result
    wait(sin_handle);
    xc = fetchOutputs(sin_handle); % cell
    
    y = yc{1};
    x = xc{1};
    

    【讨论】:

    • 感谢您的回答!我一直在玩批处理命令,发现它很慢。我发了另一个问题,你介意看一下吗?谢谢! stackoverflow.com/questions/44081110/…
    • 为什么使用batch 而不是parfevalparfeval 的语法对我来说似乎更好。
    【解决方案2】:

    您可以按照以下内容进行操作......

    funcs = {@exp,@sin} ;
    args = {2,pi/4} ;
    sols = cell(1,2) ;
    parfor n = 1:2
        sols{n}=funcs{n}(args{n});
    end
    M = sols{1} ; N = sols{2} ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2011-07-10
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多