0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-21 21:19:50 +01:00
nodejs/benchmark/cluster/echo.js
Deokjin Kim ca096563e0
benchmark: use cluster.isPrimary instead of cluster.isMaster
`cluster.isMaster` was deprecated. So need to use `cluster.isPrimary`
for benchmark.

Refs: https://github.com/nodejs/node/pull/47981
PR-URL: https://github.com/nodejs/node/pull/48002
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
2023-05-17 05:51:53 +00:00

76 lines
1.6 KiB
JavaScript

'use strict';
const cluster = require('cluster');
if (cluster.isPrimary) {
const common = require('../common.js');
const bench = common.createBenchmark(main, {
workers: [1],
payload: ['string', 'object'],
sendsPerBroadcast: [1, 10],
serialization: ['json', 'advanced'],
n: [1e5],
});
function main({
n,
workers,
sendsPerBroadcast,
payload,
serialization,
}) {
const expectedPerBroadcast = sendsPerBroadcast * workers;
let readies = 0;
let broadcasts = 0;
let msgCount = 0;
let data;
cluster.settings.serialization = serialization;
switch (payload) {
case 'string':
data = 'hello world!';
break;
case 'object':
data = { action: 'pewpewpew', powerLevel: 9001 };
break;
default:
throw new Error('Unsupported payload type');
}
for (let i = 0; i < workers; ++i)
cluster.fork().on('online', onOnline).on('message', onMessage);
function onOnline() {
if (++readies === workers) {
bench.start();
broadcast();
}
}
function broadcast() {
if (broadcasts++ === n) {
bench.end(n);
for (const id in cluster.workers)
cluster.workers[id].disconnect();
return;
}
for (const id in cluster.workers) {
const worker = cluster.workers[id];
for (let i = 0; i < sendsPerBroadcast; ++i)
worker.send(data);
}
}
function onMessage() {
if (++msgCount === expectedPerBroadcast) {
msgCount = 0;
broadcast();
}
}
}
} else {
process.on('message', (msg) => {
process.send(msg);
});
}