Why is the timing of an IPC message from a worker to the master slow? (>400ms)

Viewed 140

I currently have the Node JS (v10.9.0) code below to test the timing of a message from a child process to the master using IPC (Inter-process communication):

var cluster = require('cluster');

var masterTimer
var workerTimer

if (cluster.isMaster) {

let testWorker = cluster.fork({
    workerId : 1

})

console.log("Hi from the master")

masterTimer = process.hrtime();

testWorker.on('message', function (msg) {
    console.log(msg.message)

    console.log("Elapsed (Master): " + process.hrtime(masterTimer)[1]/1000000 + "ms")

    testWorker.destroy()
})

workerTimer = process.hrtime();
testWorker.send({message: "Message from master to worker."})


} else {
if (process.env.workerId == 1) {

    setTimeout(() => {
        process.send({ message: 'Hi from the worker!' });    
    }, 3000);

    process.on('message', function (msg) {
        console.log(msg.message)

        console.log("Elapsed (Worker): " + process.hrtime(workerTimer)[1]/1000000 + "ms")

    })
}
}

The output of this code on my 8-core MacBook Pro 2017 edition is:

Hi from the master
Message from master to worker.
Elapsed (Worker): 113.685926ms
Hi from the worker!
Elapsed (Master): 476.501366ms

This timing of a message from the worker to the master is very slow compared to a message from the master to the worker (About 4X slower in this one data-point). Also, the messaging is slow in general compared to sub-millisecond operations on individual statements. Is the code problematic or should it be this slow?

0 Answers
Related