Created
January 28, 2019 16:58
-
-
Save nathanpeck/10ddc68f2c443cfe6cda7d1a70b298f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cluster = require('cluster'); | |
const numWorkers = 4; | |
let totalTrials = 0; | |
const numOpsToRunPerTrial = 5000000; | |
if (cluster.isMaster) { | |
console.log(`Master ${process.pid} is running`); | |
// Fork workers. | |
for (let i = 0; i < numWorkers; i++) { | |
cluster.fork(); | |
} | |
function messageHandler(msg) { | |
totalTrials += msg.trials; | |
} | |
function reportAndExit() { | |
// Calculate the total ops/ms | |
const elapsedMs = process.uptime(); | |
const opsPerMs = (totalTrials * numOpsToRunPerTrial) / elapsedMs; | |
console.log(`Ops/ms: ${opsPerMs}`) | |
process.exit(); | |
} | |
// Listen for trial reports from each worker. | |
for (const id in cluster.workers) { | |
cluster.workers[id].on('message', messageHandler); | |
} | |
process.on('SIGINT', function () { | |
reportAndExit(); | |
}); | |
process.on('SIGTERM', function () { | |
reportAndExit(); | |
}); | |
} else { | |
// The payload of work to do | |
let localTrials = 0; | |
function doWork() { | |
for (let i = 0; i < numOpsToRunPerTrial; ++i) { | |
Math.sqrt(Math.random() + Math.random()); | |
} | |
localTrials++; | |
setImmediate(doWork); // Yield to the event loop to allow process signal trapping | |
} | |
doWork(); | |
console.log(`Worker ${process.pid} started`); | |
setInterval(function() { | |
process.send({trials: localTrials}); | |
localTrials = 0; | |
}, 1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment