Run parfor as for loop

10 ビュー (過去 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 Center および File ExchangeParallel Computing Fundamentals についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by