Node.js cluster - optimal number of workers
<p>I have 4 cores and ran this code according to <a href="https://nodejs.org/api/cluster.html#cluster_cluster" rel="nofollow">this example</a> :</p>

<pre><code>var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

var id = 0;
if (cluster.isWorker) {
    id = cluster.worker.id;
}

var iterations = 1000000000;
console.time('Function #' + id);
for (var i = 0; i &lt; iterations; i++) {
    var test = 0;
}
console.timeEnd('Function #' + id);

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i &lt; numCPUs; i++) {
        cluster.fork();
    }
}
</code></pre>

<p>With 4 fork (the code above), I got :</p>

<blockquote>
  <p>Function #0: 1698.801ms</p>
  
  <p>Function #1: 3282.679ms</p>
  
  <p>Function #4: 3290.384ms</p>
  
  <p>Function #3: 3425.090ms</p>
  
  <p>Function #2: 3424.922ms</p>
</blockquote>

<p>With 3 fork, I got :</p>

<blockquote>
  <p>Function #0: 1695.155ms</p>
  
  <p>Function #2: 1822.867ms</p>
  
  <p>Function #3: 2444.156ms</p>
  
  <p>Function #1: 2606.680ms</p>
</blockquote>

<p>With 2 fork, I got :</p>

<blockquote>
  <p>Function #0: 1684.929ms</p>
  
  <p>Function #1: 1682.897ms</p>
  
  <p>Function #2: 1686.123ms</p>
</blockquote>

<p>I don't understand these results. Isn't <strong>1 fork/core</strong> the <strong>optimal</strong> number ? Here I see that 4 fork is not better than 2 fork.</p>