Is it possible to conditionally switch between parallel and non parallel for loops?
Show older comments
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
More Answers (1)
Sean de Wolski
on 6 Nov 2014
0 votes
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
Sean, I wonder if this is still true in recent versions. In the test below (R2013b), I see basically equivalent execution times. On the other hand, I do have the PCT installed and I wonder whether this has an influence, even though I'm not using any workers. My question to Edric was about whether I would still see this if the PCT were not there.
function test
N=1e7;
tic;
for i=1:N
sin(N);
end
toc
tic;
parfor (i=1:N,0)
sin(N);
end
toc
Edric Ellis
on 6 Nov 2014
Note that the difference in timing you're seeing there is not related to whether or not PCT is installed - and everything to do with running it outside the context of a function. PARFOR can perform much more accurate program analysis inside a function, and gets better performance.
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.
tommsch
on 3 Dec 2021
Thats actually not a good solution, since it leads to code duplication.
Categories
Find more on Startup and Shutdown 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!