Matlab Learning [002]

{} 一个并行例子


function testParallel

% matlabpool local 4; // 开启并行 (四核)
% poolobj = parpool('local',4);// 开启并行 (四核)

tic;
total = 10^5;
for i = 1 : total
% parfor (i=1:total) // 开启并行
ss(i) = inSum;
end
plot(ss);
toc;

% matlabpool close;// 开启并行
% delete(poolobj);// 开启并行

end

function s = inSum
x = abs(round(normrnd(50,40,1,1000)));
s = sum(x);
end

% 由于处理器时钟频率的限制,增加核并不意味着是计算性能的提高。
% 使用parfor有它的优点,但也有其局限性。例如,如果循环之间相互依赖,
% 而且这种依赖能够通过代码分析得到,那么执行parfor循环就会得到错误的结果。
% 如果这种依赖关系没有检测到,那么就会得到不正确的结果。

{} SPMD( Single Program Multiple Data) // 单程序多任务进行任务并行
% 同一段程序应用于不同的数据,所以一般针对随机情况并行

parpool(3)
spmd
% build magic squares in parallel
q = magic(labindex + 2);
end
for ii=1:length(q)
% plot each magic square
figure, imagesc(q{ii});
end
delete(gcp)

 

{} labindex
% Index of this worker
% The value of labindex spans from 1 to n, where n is the number of workers
% running the current job, defined by numlabs.

 

posted @ 2016-04-29 16:37  courins  阅读(136)  评论(0编辑  收藏  举报