0

Is there a simple way to write a for loop in matlab such that below a certain number (n) of iterations it is a normal for-loop, whereas above this threshold it is a parfor loop?

I want to reduce the overhead that is associated to creating a parallel pool. I tried to set the number of workers to 1 (for less than n-iterations) but still the overhead is non-negligible.

4
  • Why can't you just surround everything with an if n > 100, parfor ... else, for... end, or just start the pool in advance?
    – Dev-iL
    Feb 2, 2017 at 20:47
  • I considered these solutions .. but I don't find them satisfying..
    – Vincent.W.
    Feb 2, 2017 at 20:48
  • You might want to clarify what you expect from the desired solution, seeing how the "trivial solutions" (and probably the only ones anyway) are not good enough... Have you considered that some other part of your algorithm is possibly much more time-consuming than the creation of the pool?
    – Dev-iL
    Feb 2, 2017 at 20:50
  • 1. The program should be fast(little overhead at least) independently of a parpool being started before. 2. The code should be easy to maintain and expand, hence I don't want duplicate code segment. I thought of something like a predefined modifier for the parfor (like parpool(1) but this still induces overhead ..)
    – Vincent.W.
    Feb 2, 2017 at 20:55

1 Answer 1

2

Option 1:

Accelerating the startup of parpool (might not work on all systems and/or MATLAB versions):

distcomp.feature( 'LocalUseMpiexec', false );

(Source)

Option 2:

Set a really long timeout to the parpool, so that it surely exists whenever needed:

% This will set the idle timeout to 2 hours 
parpool('IdleTimeout', 120);
...
functionThatPossiblyCallsParfor();

% If pool is already running:
p = parpool;
p.IdleTimeout = 120;
...
functionThatPossiblyCallsParfor();

(Source)

Option 3:

if/else based on number of required iterations (this answers the question title):

if n > 1E6 % or any other appropriate limit
  parfor (...)
    someFunction(slicedInput1,slicedInput2,...);
  end
else
  for (...)
    someFunction(input1,input2,...);
  end
end
2
  • Yeah! I didn't think about putting the loop-imside into a function.. thank you
    – Vincent.W.
    Feb 2, 2017 at 21:24
  • Glad I could help :)
    – Dev-iL
    Feb 2, 2017 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.