Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
fastify
GitHub Repository: fastify/point-of-view
Path: blob/main/benchmark.js
107 views
1
'use strict'
2
3
const { readdirSync } = require('node:fs')
4
const { spawn } = require('node:child_process')
5
const autocannon = require('autocannon')
6
const { join } = require('node:path')
7
8
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
9
10
const benchmarkDir = join(__dirname, 'benchmark')
11
12
// Keep track of spawned processes and kill if runner killed
13
const processes = []
14
15
process.on('SIGINT', () => {
16
for (const p of processes) {
17
p.kill('SIGKILL')
18
}
19
process.exit()
20
})
21
22
;(async function () {
23
const benchmarkFiles = readdirSync(benchmarkDir)
24
// don't include setup file as a benchmark
25
.filter((fileName) => fileName !== 'setup.js')
26
// sort by filename length to ensure base benchmarks run first
27
.sort((a, b) => a.length - b.length)
28
29
for (const benchmarkFile of benchmarkFiles) {
30
let benchmarkProcess
31
32
try {
33
// Spawn benchmark process
34
benchmarkProcess = spawn('node', [benchmarkFile], {
35
detached: true,
36
cwd: benchmarkDir
37
})
38
39
processes.push(benchmarkProcess)
40
41
// wait for `server listening` from benchmark
42
await Promise.race([
43
new Promise((resolve) => {
44
const stdOutCb = (d) => {
45
if (d.toString().includes('server listening')) {
46
benchmarkProcess.stdout.removeListener('data', stdOutCb)
47
resolve()
48
}
49
}
50
benchmarkProcess.stdout.on('data', stdOutCb)
51
}),
52
delay(5000).then(() => Promise.reject(new Error('timed out waiting for server listening')))
53
])
54
55
// fire single initial request as warmup
56
await fetch('http://localhost:3000/')
57
58
// run autocannon
59
const result = await autocannon({
60
url: 'http://localhost:3000/',
61
connections: 100,
62
duration: 5,
63
pipelining: 10
64
})
65
if (result.non2xx > 0) {
66
throw Object.assign(new Error('Some requests did not return 200'), {
67
statusCodeStats: result.statusCodeStats
68
})
69
}
70
console.log(`${benchmarkFile}: ${result.requests.average} req/s`)
71
} catch (err) {
72
console.error(`${benchmarkFile}:`, err)
73
} finally {
74
if (benchmarkProcess) {
75
benchmarkProcess.kill('SIGKILL')
76
processes.pop()
77
}
78
}
79
}
80
})()
81
82