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.
0 个评论
采纳的回答
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
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
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
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!