Run parfor as for loop
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Kelly Kearney
le 6 Avr 2015
Réponse apportée : Moritz Poll
le 15 Juin 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.
0 commentaires
Réponse acceptée
Edric Ellis
le 7 Avr 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
2 commentaires
Matt J
le 15 Mai 2017
Unfortunately, this approach doesn't allow you to set breakpoints in the body of the parfor loop, even when getParforArg() returns zero
Plus de réponses (1)
Moritz Poll
le 15 Juin 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
0 commentaires
Voir également
Catégories
En savoir plus sur Parallel Computing Fundamentals dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!