Does arrayfun function used on a nongpu array utilise multiple cores of CPU?

3 views (last 30 days)
I am using arrayfun for nongpu arrays. The use of arrayfun reduces the computational time of my code. I wanted to know, if arrayfun utilises the multiple cores of the CPU or not and further does computations performed using arrayfun on the CPU can be considered as parallel computing or not.

Answers (1)

OCDER
OCDER on 22 Aug 2018
It doesn't appear to use multi-core, and if anything, it's slower than a regular for loop for most cases.
X = 1:1000000;
tic
Y1 = sin(X);
toc %0.0202 s
Y2 = zeros(size(X));
tic
for j = 1:numel(X)
Y2(j) = sin(X(j));
end
toc %0.0372 s
Y3 = zeros(size(X));
tic
parfor j = 1:numel(X) %4 cores
Y3(j) = sin(X(j));
end
toc %0.1092 s
tic
Y3 = arrayfun(@sin, X);
toc %0.611 s
To see if it goes out-of-order processing, which is often a sign of multi-threaded application, try this:
arrayfun(@(x) fprintf('%d\n', x), 1:100000);
you'll find the numbers print in order, even though the doc does say don't assume it will.
"You cannot specify the order in which arrayfun calculates the elements of B or rely on them being done in any particular order."
With that said, I'd avoid arrayfun if you want speed and control over your code. Instead, control the parallel processing by explicitly using parallel functions, like parfor.
  1 Comment
Walter Roberson
Walter Roberson on 22 Aug 2018
Historically, arrayfun used a regular for loop internally. These days it has become built-in and so the operating principles have become undefined.
arrayfun is unlikely to send individual instances to parallel workers, since you might be invoking a routine that used parallel workers.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!