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-loop比单个for-loop花费的时间要多得多。此外,我的PC的numCores是12,我在运行功能代码之前初始化了12个工作人员。 为什么?我的代码出了什么问题?
非常感谢! : - )
此外,并行计算环境的初始化代码如下。
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