matlab并行计算

来源:互联网 发布:装扮淘宝店铺 编辑:程序博客网 时间:2024/05/16 08:24

用到的库函数

matlabpool

  • 打开并行计算池

tic , toc

  • 计时,作为测试用

parafor

  • 并行计算的循环方式

代码

定义一个耗时的函数如下

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

编写测试代码如下

%% initclc,clearclose allmatlabpool('open' , 2); % open%% generaltic;for ii = 1:5   A_cost(ii);     endt1 = toc;fprintf('general iter cost %f seconds in sum\n' , t1);%% parallel testtic;parfor ii = 1:5   A_cost(ii);     endt1 = 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 changeendt1 = 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 changeendt1 = toc;fprintf('parallel cost %f seconds in sum\n' , t1);matlabpool('close');
1 0
原创粉丝点击