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

45 views (last 30 days)
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.

Accepted Answer

Edric Ellis
Edric Ellis on 6 Nov 2014
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 Comments
Edric Ellis
Edric Ellis on 6 Nov 2014
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.

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 6 Nov 2014
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 Comments
Matt J
Matt J on 6 Nov 2014
Ah, good to know. And you're right, when I convert my code above to an ordinary script, the parfor version slows down greatly.

Sign in to comment.

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!