Skip to content

Instantly share code, notes, and snippets.

@nathanpeck
Created January 28, 2019 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanpeck/10ddc68f2c443cfe6cda7d1a70b298f4 to your computer and use it in GitHub Desktop.
Save nathanpeck/10ddc68f2c443cfe6cda7d1a70b298f4 to your computer and use it in GitHub Desktop.
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