MATLAB 并行编程

matlab的Parallel Computing Toolbox提供并行操作。
提速方法的选择可参照:
提升性能的方法
Choose a Parallel Computing Solution

有parfor, spmd和parfeval三种方式。比较参见链接: Choose Between spmd, parfor, and parfeval
对于每个task传递的数据量比较小,每个task任务时间比较确定且耗时不是很长的时候,parfor和parleval性能会更好一些。
不同task之间需要数据通信时,用parleval和spmd。如果在一个task中,他最多只需要别的线长的output作为输入,就是parleval,如果计算过程中还需要别的线程的通信,则用spmd。

使用parfor,对indexing的设置比较严格。比如sliced variable的indexing必须是loop variable或它与常数的线性组合(i, i+a等等),其余位置为“:”。

parfeval实例:多输出

% test1.m文件
function [x,y,z]= test1(x,y)
z = x+y;
end
% test.m文件
clear all;clc;
f(1:10) = parallel.FevalFuture;% FevalFuture object,存储所有结果
magicResults = cell(1,10);
for idx = 2:11
    f(idx-1) = parfeval(@test1,3,idx,idx+2);
%     [completedIdx,val1,val2,val3] = fetchNext(f) %得等程序跑完再读数据,不能放这
end
% method 1 for output
t = tic;
for idx = 1:10
    [completedIdx,val1,val2,val3] = fetchNext(f);%有数据就先取出来
    fprintf('Got result with index: %d.\n', completedIdx);
    magicResults{completedIdx} = [val1,val2,val3];
    disp(['val1 = ',num2str(val1),', val2 = ',num2str(val2),', val3 = ',num2str(val3)]);
end
t = toc(t)
% method 2 for output
t2=tic;
[B1,B2,B3] = fetchOutputs(f);%一次性取出所有结果
t2=toc(t2)

结果

Got result with index: 1.
val1 = 2, val2 = 4, val3 = 6
Got result with index: 2.
val1 = 3, val2 = 5, val3 = 8
Got result with index: 3.
val1 = 4, val2 = 6, val3 = 10
Got result with index: 4.
val1 = 5, val2 = 7, val3 = 12
Got result with index: 5.
val1 = 6, val2 = 8, val3 = 14
Got result with index: 6.
val1 = 7, val2 = 9, val3 = 16
Got result with index: 7.
val1 = 8, val2 = 10, val3 = 18
Got result with index: 8.
val1 = 9, val2 = 11, val3 = 20
Got result with index: 9.
val1 = 10, val2 = 12, val3 = 22
Got result with index: 10.
val1 = 11, val2 = 13, val3 = 24

t = 0.18854763
t2 = 0.012707892

可见fetchOutputs存储输出的效率比fetchNext更高,即使尝试注释掉fetchNext存数据、打印的语句,速度也近乎有小十倍的差距。

clc;clear all;

% parpool(20);
parpool("threads");
t=tic;
spmd
% build magic squares in parallel
q = magic(labindex + 2);
disp(['当前worker编号:' num2str(labindex)])
end
t = toc(t);
disp(['time cost for spmd:',num2str(t)]);
for ii=1:length(q)
% plot each magic square
figure, imagesc(q{ii}); % q就是一个composite变量
end
delete(gcp('nocreate'))
clear all;
t=tic;
for i = 1:20
% build magic squares in parallel
q = magic(i + 2);
disp(['当前worker编号:' num2str(labindex)])
end
t = toc(t);
disp(['time cost for for loop:',num2str(t)]);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值