I'm trying to understand why a simple do-loop takes substantially longer when done in parallel than sequentially:
count = 0;
SetSharedVariable[count];
AbsoluteTiming[Do[count++, {nn, 100}]]
Print[count]
Out[493]= {0.000176, Null} (\*Time in seconds*)
Out[494]= 100 (\*The result*)
Whereas if I do
count = 0;
SetSharedVariable[count];
AbsoluteTiming[ParallelDo[count++, {nn, 100}]]
Print[count]
Out[497]= {0.391256, Null} (\*Time in seconds*)
Out[498]= 100 (\*The result*)
Could someone please explain why ParallelDo takes 0.39 seconds whereas Do takes only 0.00017 seconds?
Thanks!
SetSharedVariableforcescountto be always evaluated on the main kernel. Thus you gain nothing, but you do lose a lot: evaluation will keep switching between parallel kernels and the main kernel, adding a considerable overhead. – Szabolcs Jun 20 '14 at 14:57SetSharedVariable[count]first, thenParallelEvaluate[Information[count]]. It's a very straightforward implementation. – Szabolcs Jun 20 '14 at 15:27Doloops instead ofParallelDoloops because of the communication overhead? – MvP Jun 20 '14 at 15:42SetSharedVariableis only useful if the variable access is infrequent and takes negligible time compared to other computations. I only foundSetSharedVariableuseful in very few cases. – Szabolcs Jun 20 '14 at 15:46