MATLAB: How use all cpu cores

parfor cores

Hi everyone.
I want to know how would I use the parfor statement (if it's possible) or something similar to get optimal CPU use.
I have a i7 7700k processor, which has 4 cores and 8 threads.
For example, if I run this code to calculate number pi:
% START
clear all
format long
d=1e-09;
tic
a=0;
for i=0:d:1
a=a+sqrt(1-i*i)*d;
end
toc
p=(a-atan(1))*4
% END

I obtain:
Elapsed time is 26.742359 seconds.
p =
1.999863386004108e-09
where "p" is the difference between the number I'm calculating and the number pi.
So now, if I cut the "for" statement in four parts (all of them independent of each other), I obtain:
%START
clear all
format long
d=1e-09;
tic
a1=0;
a2=0;
a3=0;
a4=0;
for i=0:d:1/4-d
a1=a1+sqrt(1-i*i)*d;
end
for i=1/4:d:2/4-d
a2=a2+sqrt(1-i*i)*d;
end
for i=2/4:d:3/4-d
a3=a3+sqrt(1-i*i)*d;
end
for i=3/4:d:1
a4=a4+sqrt(1-i*i)*d;
end
a=a1+a2+a3+a4;
toc
p=(a-atan(1))*4
% END
getting this result:
Elapsed time is 26.957344 seconds.
p =
2.000035692617530e-09
which is practically the same result (in time and calculation).
In both cases, the use of the total CPU is 14%.
So I want to assignate, in the second case, one core per "for" statement (I mean, core 1 to calculate a1, core 2 to calculate a2, and so on), and when the four calculations are finalized, and only then, calculate "a". Time processing would be four times shorter? Is possible to do that?
Thanks for your time!

Best Answer

a = zeros(1,4);
parfor s = 1 : 4
b = 0;
for i = (s-1)/4 : d: s/4-d
b = b + sqrt(1-i*i) * d;
end
a(s) = b;
end
Note: your code has the upper ranges end at something minus d for the a1, a2, a3, but for a4 the upper range ends at 1 instead of 1 - d. Your code would therefore do one extra iteration for a4, and that is not coded for here. However, when i becomes 1 exactly for a4, then sqrt(1-i*i) becomes 0, and so the iteration would have been wasted, for this particular formula. In the more general case, that final iteration might be needed, so remember to account for the boundary conditions carefully.