matlab并行计算

用到的库函数

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');
    

你可能感兴趣的:(matlab,并行计算)