• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common.js');
3const { spawn } = require('child_process');
4const path = require('path');
5
6let Worker;  // Lazy loaded in main
7
8const bench = common.createBenchmark(main, {
9  dur: [1],
10  script: [
11    'benchmark/fixtures/require-builtins',
12    'benchmark/fixtures/require-cachable',
13    'test/fixtures/semicolon',
14  ],
15  mode: ['process', 'worker']
16}, {
17  flags: ['--expose-internals']
18});
19
20function spawnProcess(script) {
21  const cmd = process.execPath || process.argv[0];
22  const argv = ['--expose-internals', script];
23  return spawn(cmd, argv);
24}
25
26function spawnWorker(script) {
27  return new Worker(script, { stderr: true, stdout: true });
28}
29
30function start(state, script, bench, getNode) {
31  const node = getNode(script);
32  let stdout = '';
33  let stderr = '';
34
35  node.stdout.on('data', (data) => {
36    stdout += data;
37  });
38
39  node.stderr.on('data', (data) => {
40    stderr += data;
41  });
42
43  node.on('exit', (code) => {
44    if (code !== 0) {
45      console.error('------ stdout ------');
46      console.error(stdout);
47      console.error('------ stderr ------');
48      console.error(stderr);
49      throw new Error(`Error during node startup, exit code ${code}`);
50    }
51    state.throughput++;
52
53    if (state.go) {
54      start(state, script, bench, getNode);
55    } else {
56      bench.end(state.throughput);
57    }
58  });
59}
60
61function main({ dur, script, mode }) {
62  const state = {
63    go: true,
64    throughput: 0
65  };
66
67  setTimeout(() => {
68    state.go = false;
69  }, dur * 1000);
70
71  script = path.resolve(__dirname, '../../', `${script}.js`);
72  if (mode === 'worker') {
73    Worker = require('worker_threads').Worker;
74    bench.start();
75    start(state, script, bench, spawnWorker);
76  } else {
77    bench.start();
78    start(state, script, bench, spawnProcess);
79  }
80}
81