Run parfor as for loop

조회 수: 8 (최근 30일)
Kelly Kearney
Kelly Kearney 2015년 4월 6일
답변: Moritz Poll 2021년 6월 15일
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.

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Moritz Poll
Moritz Poll 2021년 6월 15일
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

카테고리

Help CenterFile Exchange에서 Parallel Computing Fundamentals에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by