Is it possible to conditionally switch between parallel and non parallel for loops?

17 ビュー (過去 30 日間)
I would like to be able to set a flag as the input to a function that changes the code from executing a for loop to a parfor loop and vice versa.
It would be handy sometimes so I can debug the contents of the loop (in a standard for) without actually changing the function around it.

採用された回答

Edric Ellis
Edric Ellis 2014 年 11 月 6 日
You can do this by setting the optional "number of workers" argument to 0. For example
runInSerial = <...>;
if runInSerial
parforArg = 0;
else
parforArg = Inf;
end
parfor (idx = 1:N, parforArg)
...
end
  4 件のコメント
Edric Ellis
Edric Ellis 2014 年 11 月 6 日
MATLAB without Parallel Computing Toolbox supports the "number of workers" argument (and ignores it). It doesn't change the performance - in all cases, even if "number of workers" is zero, the loop still runs as a PARFOR (in the sense that all the PARFOR constraints apply etc.) - it simply runs locally in the MATLAB process rather than using a pool.
Gideon Kogan
Gideon Kogan 2019 年 6 月 2 日
Dear Edric Ellis, there was no clear answer before indication of the alternatives. Is the answer is no?

サインインしてコメントする。

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2014 年 11 月 6 日
I would just write two separate subfunctions one which uses parfor and one that doesn't. Parfor without any workers will be less efficient than a regular for-loop. If the parallel flag is on, call one, else, call the other.
  4 件のコメント
Matt J
Matt J 2014 年 11 月 6 日
Ah, good to know. And you're right, when I convert my code above to an ordinary script, the parfor version slows down greatly.
tommsch
tommsch 2021 年 12 月 3 日
Thats actually not a good solution, since it leads to code duplication.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeParallel for-Loops (parfor) についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by