-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy pathecho.js
73 lines (63 loc) Β· 1.58 KB
/
echo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
const common = require('../common.js');
const path = require('path');
const bench = common.createBenchmark(main, {
workers: [1],
payload: ['string', 'object'],
sendsPerBroadcast: [1, 10],
n: [1e5]
}, { flags: ['--experimental-worker'] });
const workerPath = path.resolve(__dirname, '..', 'fixtures', 'echo.worker.js');
function main(conf) {
const { Worker } = require('worker_threads');
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();
}
}
}