function test_parfor
N = 1e8;
sum_all = 0; % sum all numbers
sum_odd = 0; % sum odd numbers
sum_even = 0; % sum even numbers
tic;
parfor i = 1 : N
sum_all = sum_all + i; % sum all numbers
if mod(i,2)
sum_odd = sum_odd + i; % sum odd numbers
else
sum_even = sum_even + i; % sum even numbers
end %endif
end %endfor
toc;
fprintf('sum_all=%d,\nsum_odd=%d,\nsum_even=%d.\n', ...
sum_all, sum_odd, sum_even);
我已经初始化了 parpool 环境并运行了上面的代码。但是,parfor 循环比单个 for 循环花费的时间要多得多。此外,我的 PC 的 numCores 为 12,并且在运行功能代码之前我已经初始化了 12 个 worker。为什么?我的代码有什么问题?
非常感谢你!:-)
另外,并行计算环境的初始化代码如下。
function initpar(CoreNum)
%Initialize Matlab Parallel Computing Enviornment
if nargin==0
CoreNum=feature('numCores');
end
if isempty(gcp('nocreate'))
clear ALL;
parpool('local',CoreNum); % matlabpool in R2013
else
disp('Parallel Computing Enviornment already initialized');
end