Run parfor as for loop

8 views (last 30 days)
Kelly Kearney
Kelly Kearney on 6 Apr 2015
Answered: Moritz Poll on 15 Jun 2021
In previous versions of Matlab, if I ran a parfor loop without first calling matlabpool, it would execute as a serial for loop. This made it easy to run portions of my code either way with a simple switch. However, in recent versions, the default preference is to start a new pool automatically when a parfor is encountered, so the loop is run in parallel regardless of whether I set up a parallel pool ahead of time.
Is there a way to programatically disable this behavior while running a function? I can change the preferences in my own version, but so far I haven't found a way to make sure this setting isn't active when someone else runs the code on their computer.

Accepted Answer

Edric Ellis
Edric Ellis on 7 Apr 2015
Unfortunately there is no programmatic way to change the preference. What you can do is use the optional argument to parfor that specifies the number of workers to use. You could do something like this:
% Create a helper function to choose the NumWorkers argument to PARFOR
function arg = getParforArg()
p = gcp('nocreate'); % get the pool object if it exists, but never open a pool
if isempty(p)
arg = 0;
else
arg = p.NumWorkers;
end
end
% Then, use that in your PARFOR loops.
parfor (idx = 1:10, getParforArg())
... do stuff ...
end
The optional argument to parfor is described in the reference page.
  2 Comments
Kelly Kearney
Kelly Kearney on 7 Apr 2015
Thanks, that does the trick!
Matt J
Matt J on 15 May 2017
Unfortunately, this approach doesn't allow you to set breakpoints in the body of the parfor loop, even when getParforArg() returns zero

Sign in to comment.

More Answers (1)

Moritz Poll
Moritz Poll on 15 Jun 2021
In case anyone comes across this question in 2021 or later, it seems that setting the number of workers to zero does the trick. For example:
if feature('numcores') > 0
M = feature('numcores');
else
M = 0;
end
parfor (i = 1:10, M)
% do something in parallel or serially depending on how many cores the
% machine has you are running on. Useful when running on a server that
% let's you decide how many CPUs to allocate. If you allocate only one,
% this will run serially.
end

Categories

Find more on Parallel Computing Fundamentals in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!