-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbenchmark-compare.mjs
188 lines (157 loc) · 5.26 KB
/
benchmark-compare.mjs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env node
'use strict'
import { createRequire } from 'module'
import chalk from 'chalk'
import { info } from './lib/packages.mjs'
import { compare } from './lib/autocannon.mjs'
import inquirer from 'inquirer'
const require = createRequire(import.meta.url)
const os = require('os')
const commander = require('commander')
// const inquirer = require('inquirer')
const Table = require('cli-table3')
const { join } = require('path')
const { readdirSync, readFileSync, writeFileSync } = require('fs')
const resultsPath = join(process.cwd(), 'results')
commander
.option('-t, --table', 'print table')
.option('-m --markdown', 'format table for markdown')
.option('-u --update', 'update README.md')
.parse(process.argv)
const opts = commander.opts()
if (opts.markdown || opts.update) {
chalk.level = 0
}
if (!getAvailableResults().length) {
console.log(chalk.red('Benchmark to gather some results to compare.'))
} else if (opts.update) {
updateReadme()
} else if (opts.table) {
console.log(compareResults(opts.markdown))
} else {
compareResultsInteractive()
}
function getAvailableResults () {
return readdirSync(resultsPath)
.filter((file) => file.match(/(.+)\.json$/))
.sort()
.map((choice) => choice.replace('.json', ''))
}
function formatHasRouter (hasRouter) {
return typeof hasRouter === 'string' ? hasRouter : (hasRouter ? '✓' : '✗')
}
function updateReadme () {
const machineInfo = `${os.platform()} ${os.arch()} | ${os.cpus().length} vCPUs | ${(os.totalmem() / (1024 ** 3)).toFixed(1)}GB Mem`
const benchmarkMd = `# Benchmarks
* __Machine:__ ${machineInfo}
* __Node:__ \`${process.version}\`
* __Run:__ ${new Date()}
* __Method:__ \`autocannon -c 50 -d 20 -p 5 localhost:3000\` (two rounds; one to warm-up, one to measure)
${compareResults(true)}
`
const md = readFileSync('README.md', 'utf8')
writeFileSync('README.md', md.split('# Benchmarks')[0] + benchmarkMd, 'utf8')
}
function compareResults (markdown) {
const tableStyle = !markdown
? {}
: {
chars: {
top: '',
'top-left': '',
'top-mid': '',
'top-right': '',
bottom: '',
'bottom-left': '',
'bottom-mid': '',
'bottom-right': '',
mid: '',
'left-mid': '',
'mid-mid': '',
'right-mid': '',
left: '|',
right: '|',
middle: '|'
},
style: {
border: [],
head: []
}
}
const table = new Table({
...tableStyle,
head: ['', 'Version', 'Router', 'Requests/s', 'Latency (ms)', 'Throughput/Mb']
})
if (markdown) {
table.push([':--', '--:', '--:', ':-:', '--:', '--:'])
}
const results = getAvailableResults().map(file => {
const content = readFileSync(`${resultsPath}/${file}.json`)
return JSON.parse(content.toString())
}).sort((a, b) => parseFloat(b.requests.mean) - parseFloat(a.requests.mean))
const outputResults = []
const formatThroughput = throughput => throughput ? (throughput / 1024 / 1024).toFixed(2) : 'N/A'
for (const result of results) {
const beBold = result.server === 'fastify'
const { hasRouter, version } = info(result.server) || {}
const {
requests: { average: requests },
latency: { average: latency },
throughput: { average: throughput }
} = result
outputResults.push(
{
name: result.server,
version,
hasRouter,
requests: requests ? requests.toFixed(1) : 'N/A',
latency: latency ? latency.toFixed(2) : 'N/A',
throughput: formatThroughput(throughput)
}
)
table.push([
bold(beBold, chalk.blue(result.server)),
bold(beBold, version),
bold(beBold, formatHasRouter(hasRouter)),
bold(beBold, requests ? requests.toFixed(1) : 'N/A'),
bold(beBold, latency ? latency.toFixed(2) : 'N/A'),
bold(beBold, throughput ? (throughput / 1024 / 1024).toFixed(2) : 'N/A')
])
}
writeFileSync('benchmark-results.json', JSON.stringify(outputResults), 'utf8')
return table.toString()
}
async function compareResultsInteractive () {
let choices = getAvailableResults()
const firstChoice = await inquirer.prompt([{
type: 'list',
name: 'choice',
message: 'What\'s your first pick?',
choices
}])
choices = choices.filter(choice => choice !== firstChoice.choice)
const secondChoice = await inquirer.prompt([{
type: 'list',
name: 'choice',
message: 'What\'s your second one?',
choices
}])
const [a, b] = [firstChoice.choice, secondChoice.choice]
const result = compare(a, b)
const fastest = chalk.bold.yellow(result.fastest)
const fastestAverage = chalk.green(result.fastestAverage)
const slowest = chalk.bold.yellow(result.slowest)
const slowestAverage = chalk.green(result.slowestAverage)
const diff = chalk.bold.green(result.diff)
if (result === true) {
console.log(chalk.green.bold(`${a} and ${b} both are fast!`))
return
}
console.log(`
${chalk.blue('Both are awesome but')} ${fastest} ${chalk.blue('is')} ${diff} ${chalk.blue('faster than')} ${slowest}
• ${fastest} ${chalk.blue('request average is')} ${fastestAverage}
• ${slowest} ${chalk.blue('request average is')} ${slowestAverage}`)
}
function bold (writeBold, str) {
return writeBold ? chalk.bold(str) : str
}