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 allformat longd=1e-09;tica=0;for i=0:d:1a=a+sqrt(1-i*i)*d;endtocp=(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 allformat longd=1e-09;tica1=0;a2=0;a3=0;a4=0;for i=0:d:1/4-da1=a1+sqrt(1-i*i)*d;endfor i=1/4:d:2/4-da2=a2+sqrt(1-i*i)*d;endfor i=2/4:d:3/4-da3=a3+sqrt(1-i*i)*d;endfor i=3/4:d:1a4=a4+sqrt(1-i*i)*d;enda=a1+a2+a3+a4;tocp=(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