User`s guide
Improving parfor Performance
2-43
before the loop (as shown on the left below), rather than have each worker create its own
arrays inside the loop (as shown on the right).
Try the following examples running a parallel pool locally, and notice the difference in
time execution for each loop. First open a local parallel pool:
parpool('local')
Then enter the following examples. (If you are viewing this documentation in the
MATLAB help browser, highlight each segment of code below, right-click, and select
Evaluate Selection in the context menu to execute the block in MATLAB. That way the
time measurement will not include the time required to paste or type.)
tic;
n = 200;
M = magic(n);
R = rand(n);
parfor i = 1:n
A(i) = sum(M(i,:).*R(n+1-i,:));
end
toc
tic;
n = 200;
parfor i = 1:n
M = magic(n);
R = rand(n);
A(i) = sum(M(i,:).*R(n+1-i,:));
end
toc
Running on a remote cluster, you might find different behavior, as workers can
simultaneously create their arrays, saving transfer time. Therefore, code that is
optimized for local workers might not be optimized for cluster workers, and vice versa.