for / parfor within if

18 ビュー (過去 30 日間)
Eric
Eric 2019 年 11 月 21 日
コメント済み: Jason Ross 2019 年 11 月 22 日
Is there a way to write something like:
if parallelloop
parfor i=1:n
else
for i=1:n
end
...iterations
end
where parallellop is a boolean.
This code is not accepted by Matlab because the same end for both parfor and for.
A solution I do not accept for many reasons would be:
if parallelloop
parfor i=1:n
...iterations
end
else
for i=1:n
...iterations
end
end
Another solution I would like to have is an #ifdef like approach, but is there any?
Thanks by advance.
  2 件のコメント
Philippe Lebel
Philippe Lebel 2019 年 11 月 21 日
編集済み: Philippe Lebel 2019 年 11 月 21 日
what are the reasons why you dont want to put the end statments after the parfor and the for?
Eric
Eric 2019 年 11 月 22 日
Because the code between for and end statements is too long and also if this writing can be done it can be written in a function with a genric name that will perform a parfor loop or a simple for loop, depending on the capabilities of the Matlab.
Just as a comparizon, I have the same approach with openMP and C++, the same code with preprocessor directives and if openMP is installed it is used, otherwise it is not. And I think that many people using distcomp would like to have this flexibility: a single code for many platforms/architectures.

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

回答 (1 件)

Jason Ross
Jason Ross 2019 年 11 月 21 日
You can control if a loop is run with parallel workers or not by changing the number of workers. See "Test parfor-Loops by Switching Between Parallel and Serial Execution" in the parfor documentation. Note that even with 0 workers, the parfor is still nondeterministic.
To make your example work, you would set the number of workers to 0 if parallelloop is false.
  4 件のコメント
Eric
Eric 2019 年 11 月 22 日
You are partially right because:
  1. computational time is not the same (as seen in your link) and
  2. parfor is not known on old versions of Matlab (mine is R2007 and parfor is not known).
Jason Ross
Jason Ross 2019 年 11 月 22 日
There have been a lot of changes since then -- the computational time issue might have been a bug, and fixed. The overall point I was getting at was that parfor is interpreted as a for in the absence of Parallel Computing Toolbox being present.
This also does make the implicit assumption that parfor introduces new functionality that would be incompatible with releases that don't know what parfor is, but that's going to be the case with pretty much any arbitrary software package.

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

カテゴリ

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

製品


リリース

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by