Skip to content
This repository has been archived by the owner on Aug 31, 2018. It is now read-only.

benchmark: port cluster/echo to worker #115

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions benchmark/fixtures/echo.worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

const worker = require('worker');

worker.on('workerMessage', (msg) => {
worker.postMessage(msg);
});
72 changes: 72 additions & 0 deletions benchmark/worker/echo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
'use strict';

const { Worker } = require('worker');
const common = require('../common.js');
const path = require('path');
const bench = common.createBenchmark(main, {
workers: [1],
payload: ['string', 'object'],
sendsPerBroadcast: [1, 10],
n: [1e5]
});

const workerPath = path.resolve(__dirname, '..', 'fixtures', 'echo.worker.js');

function main(conf) {
const n = +conf.n;
const workers = +conf.workers;
const sends = +conf.sendsPerBroadcast;
const expectedPerBroadcast = sends * workers;
var payload;
var readies = 0;
var broadcasts = 0;
var msgCount = 0;

switch (conf.payload) {
case 'string':
payload = 'hello world!';
break;
case 'object':
payload = { action: 'pewpewpew', powerLevel: 9001 };
break;
default:
throw new Error('Unsupported payload type');
}

const workerObjs = [];

for (var i = 0; i < workers; ++i) {
const worker = new Worker(workerPath);
workerObjs.push(worker);
worker.on('online', onOnline);
worker.on('message', onMessage);
}

function onOnline() {
if (++readies === workers) {
bench.start();
broadcast();
}
}

function broadcast() {
if (broadcasts++ === n) {
bench.end(n);
for (const worker of workerObjs) {
worker.unref();
}
return;
}
for (const worker of workerObjs) {
for (var i = 0; i < sends; ++i)
worker.postMessage(payload);
}
}

function onMessage() {
if (++msgCount === expectedPerBroadcast) {
msgCount = 0;
broadcast();
}
}
}