# Best Parallel Kernel Configuration

I wrote a code snippet which counts prime numbers in any given interval because the built-in PrimePihas a limited bounds.

AbsoluteTiming[Sum[If[PrimeQ[n], 1, 0], {n, 10^7, 10^8}]]


{113.9780866, 5096876}

I also wrote a parallel version of the above code:

AbsoluteTiming[ParallelSum[If[PrimeQ[n], 1, 0], {n, 10^7, 10^8}]]


8 kernels {57.3633016, 5096876}

6 kernels {55.6611571, 5096876}

4 kernels {55.030738, 5096876}

2 kernels {71.8839868, 5096876}

The test machine has a Core i5 processor with 2 cores and 4 threads. In Parallel Kernel Configuration, Mathematica suggests having the number of kernels equal to the number of cores (here 2). However, as you can see in my results, the optimal choice is to set the number of kernels equal to the number of threads.

I know each thread has its own stack. The better performance for threads originates from this? Or some other reasons?

-
20% accept rate is not much, really... –  stevenvh Dec 23 '12 at 16:40
@stevenvh, I don't 'accept' trivial non-useful answers. That's why. –  Mohsen Afshin Dec 23 '12 at 17:02
Even if you had a million threads, each would still have its own stack. Actually, your conclusion here is not generalizable: whether better performance is obtained with two or four kernels depends on the code in question. This is due to the technicalities of simultaneous multithreading on modern processors rather than Mathematica, per se. I could elaborate, but this has been described quite well elsewhere already: here is a good overview, for example. –  Oleksandr R. Dec 25 '12 at 4:03
Probably in the 4 kernels case the overhead from the context switching was less than the gain of adding two more kernels. –  Spawn1701D Apr 8 at 0:53