您的位置:首页 > 编程语言 > MATLAB

matlab并行计算

2015-12-10 12:35 507 查看

用到的库函数

matlabpool

打开并行计算池

tic , toc

计时,作为测试用

parafor

并行计算的循环方式

代码

定义一个耗时的函数如下

function A_cost( n )
pause(n)
fprintf('A_cost execute finished,cost %d senconds!!\n',n);
end


编写测试代码如下

%% init
clc,clear
close all

matlabpool('open' , 2); % open
%% general
tic;
for ii = 1:5
A_cost(ii);
end
t1 = toc;
fprintf('general iter cost %f seconds in sum\n' , t1);

%% parallel test
tic;
parfor ii = 1:5
A_cost(ii);
end
t1 = toc;
fprintf('parallel cost %f seconds in sum\n' , t1);
matlabpool('close'); % close


结果如下



注意

并行计算池打开相关

我的电脑只能打开2个并行计算池,不同的电脑应该不一样,打开的个数超过限制时,matlab会报错并提醒

循环相关

在parfor的循环过程中,不能对循环变量进行重新赋值,否则会提示错误

多次对某个值重写时,最终运行结束该值为0,如下面的程序

matlabpool('open' , 2);
tic;
parfor ii = 1:5
%ii = A_cost(ii); % will cause error
%test = ii + A_cost(ii); % test will not change
test = A_cost(ii); % test will change
end
t1 = toc;
fprintf('parallel cost %f seconds in sum\n' , t1);
matlabpool('close');


而下面的程序运行结束之后test为[1,2,3,4,5]

matlabpool('open' , 2);
tic;
parfor ii = 1:5
%ii = A_cost(ii); % will cause error
%test = ii + A_cost(ii); % test will not change
test(ii) = A_cost(ii); % test will change
end
t1 = toc;
fprintf('parallel cost %f seconds in sum\n' , t1);
matlabpool('close');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: