How use all cpu cores?
Show older comments
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!
Accepted Answer
More Answers (1)
John D'Errico
on 7 Jun 2017
0 votes
It is possible ONLY if you have the parallel computing toolbox. Otherwise, you can want for MATLAB to know what it is that you want to do, but it just won't happen.
Of course, if you happen to have the mindreading toolbox, then you need not write any code at all, and MATLAB will just do as you wish. This toolbox seems to be forever under beta test though.
Categories
Find more on Parallel Computing Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!