Run parfor as for loop

8 visualizzazioni (ultimi 30 giorni)
Kelly Kearney
Kelly Kearney il 6 Apr 2015
Risposto: Moritz Poll il 15 Giu 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.

Risposta accettata

Edric Ellis
Edric Ellis il 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 Commenti
Kelly Kearney
Kelly Kearney il 7 Apr 2015
Thanks, that does the trick!
Matt J
Matt J il 15 Mag 2017
Unfortunately, this approach doesn't allow you to set breakpoints in the body of the parfor loop, even when getParforArg() returns zero

Accedi per commentare.

Più risposte (1)

Moritz Poll
Moritz Poll il 15 Giu 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

Categorie

Scopri di più su Parallel Computing Fundamentals in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by