• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const cluster = require('cluster');
4if (cluster.isMaster) {
5  const common = require('../common.js');
6  const bench = common.createBenchmark(main, {
7    workers: [1],
8    payload: ['string', 'object'],
9    sendsPerBroadcast: [1, 10],
10    serialization: ['json', 'advanced'],
11    n: [1e5]
12  });
13
14  function main({
15    n,
16    workers,
17    sendsPerBroadcast,
18    payload,
19    serialization
20  }) {
21    const expectedPerBroadcast = sendsPerBroadcast * workers;
22    let readies = 0;
23    let broadcasts = 0;
24    let msgCount = 0;
25    let data;
26
27    cluster.settings.serialization = serialization;
28
29    switch (payload) {
30      case 'string':
31        data = 'hello world!';
32        break;
33      case 'object':
34        data = { action: 'pewpewpew', powerLevel: 9001 };
35        break;
36      default:
37        throw new Error('Unsupported payload type');
38    }
39
40    for (let i = 0; i < workers; ++i)
41      cluster.fork().on('online', onOnline).on('message', onMessage);
42
43    function onOnline() {
44      if (++readies === workers) {
45        bench.start();
46        broadcast();
47      }
48    }
49
50    function broadcast() {
51      if (broadcasts++ === n) {
52        bench.end(n);
53        for (const id in cluster.workers)
54          cluster.workers[id].disconnect();
55        return;
56      }
57      for (const id in cluster.workers) {
58        const worker = cluster.workers[id];
59        for (let i = 0; i < sendsPerBroadcast; ++i)
60          worker.send(data);
61      }
62    }
63
64    function onMessage() {
65      if (++msgCount === expectedPerBroadcast) {
66        msgCount = 0;
67        broadcast();
68      }
69    }
70  }
71} else {
72  process.on('message', (msg) => {
73    process.send(msg);
74  });
75}
76