Skip to content

Commit 08233d5

Browse files
committed
Make bench code slightly less ugly
1 parent e0d130c commit 08233d5

2 files changed

Lines changed: 100 additions & 79 deletions

File tree

bench/index.js

Lines changed: 45 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -17,31 +17,36 @@ const results = []
1717
const benchId = 301
1818
const children = {}
1919
const memory = {}
20-
let lob = process.argv[2] === '--lob' || process.argv[2] === 'lob'
20+
21+
const lob = process.argv[2] === '--lob' || process.argv[2] === 'lob'
22+
2123
Promise.all(Object.keys(ports).map((k) => new Promise((resolve, reject) => {
22-
let child = children[k] = fork(join(__dirname, 'server'), [k, lob ? 'lob' : ''])
24+
const child = children[k] = fork(join(__dirname, 'server'), [k, lob ? 'lob' : ''])
2325
child.once('error', (err) => {
2426
console.log(err)
2527
process.exit()
2628
})
29+
2730
let started
2831
let gotMemory
2932
child.on('message', (m) => {
30-
let endMem = m.match(/^endMem(.*)/)
33+
const endMem = m.match(/^endMem(.*)/)
3134
if (endMem) {
3235
memory[k].end = endMem[1]
3336
child.kill()
3437
}
38+
3539
started = started || m === k
36-
let startMem = m.match(/^startMem(.*)/)
40+
const startMem = m.match(/^startMem(.*)/)
3741
gotMemory = gotMemory || startMem
38-
if (startMem) memory[k] = {start: startMem[1]}
42+
43+
if (startMem) memory[k] = { start: startMem[1] }
3944
if (gotMemory && started) return resolve()
4045
})
4146
}))).then(() => bench())
4247

4348
const urlTemplate = (port, string) => {
44-
let url = {host: 'localhost', port, path: `/bench/${benchId}`}
49+
const url = { host: 'localhost', port, path: `/bench/${benchId}` }
4550
return string ? `http://${url.host}:${url.port}${url.path}` : url
4651
}
4752

@@ -57,46 +62,47 @@ const shuffler = (array) => {
5762

5863
const formatBytes = (bytes) => {
5964
if (bytes === 0) return '0 Byte'
60-
let k = 1000
61-
let dm = 2
62-
let sizes = ['Bytes', 'KB', 'MB', 'GB']
63-
let i = Math.floor(Math.log(bytes) / Math.log(k))
65+
const k = 1000
66+
const dm = 2
67+
const sizes = ['Bytes', 'KB', 'MB', 'GB']
68+
const i = Math.floor(Math.log(bytes) / Math.log(k))
6469
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
6570
}
6671

6772
// benchamrks
6873
const bencher = (title) => new Promise((resolve, reject) => {
6974
console.log(`benchmarking ${title}`)
70-
let port = ports[title]
71-
let done = (err, res) => {
75+
const port = ports[title]
76+
const done = (err, res) => {
7277
if (err) return reject(err)
7378
results.push(res)
7479
return resolve(title)
7580
}
76-
let acOpts = {
81+
const acOpts = {
7782
url: urlTemplate(port, true),
7883
title,
7984
connections: lob ? 10 : 50,
8085
pipelining: lob ? 1 : 10,
81-
headers: {'accept-encoding': 'gzip, deflate, br'}
86+
headers: { 'accept-encoding': 'gzip, deflate, br' }
8287
}
83-
autocannon(Object.assign({duration: 3}, acOpts), () => {
84-
autocannon(Object.assign({duration: 7}, acOpts), done)
88+
autocannon(Object.assign({ duration: 3 }, acOpts), () => {
89+
autocannon(Object.assign({ duration: 7 }, acOpts), done)
8590
})
8691
})
8792

8893
let last = {}
8994
const checkConsistency = async (name) => {
90-
let port = ports[name]
95+
const port = ports[name]
9196
let { data, headers } = await get(urlTemplate(port, true))
92-
let isJSON = headers['content-type'].indexOf('application/json') !== -1
97+
const isJSON = headers['content-type'].indexOf('application/json') !== -1
9398
data = `${JSON.stringify(data)}-isJson:${isJSON}`
99+
94100
if (!data || (last.lib && last.result !== data)) {
95-
let err = new Error(`Got inconsistent results from libraries`)
101+
const err = new Error(`Got inconsistent results from libraries`)
96102
err.meta = [`${last.lib} - ${last.result}`, `${name} - ${data}`]
97103
throw err
98104
}
99-
last = {lib: name, result: data}
105+
last = { lib: name, result: data }
100106
}
101107

102108
const getEndMemory = (name) => new Promise((resolve, reject) => {
@@ -106,28 +112,32 @@ const getEndMemory = (name) => new Promise((resolve, reject) => {
106112

107113
async function bench () {
108114
console.log(`servers running, starting benchmarks\n`)
109-
let keys = shuffler(Object.keys(ports))
110-
for (let name of keys) {
115+
const keys = shuffler(Object.keys(ports))
116+
117+
for (const name of keys) {
111118
try {
112119
await checkConsistency(name)
113120
} catch (ex) {
114121
console.log(ex, name)
115122
process.exit()
116123
}
117124
}
118-
for (let name of keys) await bencher(name)
119-
for (let name of keys) await getEndMemory(name)
120-
let head = [
121-
{alias: 'lib', width: 12},
122-
{alias: 'req/sec', width: 12},
123-
{alias: 'latency', width: 12},
124-
{alias: 'throughput', width: 14},
125-
{alias: 'errors', width: 11},
126-
{alias: 'memory (start)'},
127-
{alias: 'memory (end)'}
128-
].map((h) => Object.assign({paddingLeft: 0, paddingRight: 0}, h))
125+
126+
for (const name of keys) await bencher(name)
127+
for (const name of keys) await getEndMemory(name)
128+
129+
const head = [
130+
{ alias: 'lib', width: 12 },
131+
{ alias: 'req/sec', width: 12 },
132+
{ alias: 'latency', width: 12 },
133+
{ alias: 'throughput', width: 14 },
134+
{ alias: 'errors', width: 11 },
135+
{ alias: 'memory (start)' },
136+
{ alias: 'memory (end)' }
137+
].map((h) => Object.assign({ paddingLeft: 0, paddingRight: 0 }, h))
138+
129139
results.sort((a, b) => b.requests.average - a.requests.average)
130-
let rows = results.map((r) => [
140+
const rows = results.map((r) => [
131141
r.title,
132142
r.requests.average,
133143
r.latency.average,
@@ -136,6 +146,7 @@ async function bench () {
136146
memory[r.title].start.split('/').map(formatBytes).join('\n'),
137147
memory[r.title].end.split('/').map(formatBytes).join('\n')
138148
])
149+
139150
console.log(table(head, rows).render())
140151
process.exit()
141152
}

bench/server.js

Lines changed: 55 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -9,63 +9,73 @@ const ports = {
99
express: 3014,
1010
hapi: 3015
1111
}
12+
1213
const logStart = (n) => {
1314
process.send(n)
1415
let { heapUsed, heapTotal } = process.memoryUsage()
1516
process.send(`startMem${heapUsed}/${heapTotal}`)
1617
}
18+
1719
process.on('message', (m) => {
1820
if (m === 'endMemory') {
1921
let { heapUsed, heapTotal } = process.memoryUsage()
2022
return process.send(`endMem${heapUsed}/${heapTotal}`)
2123
}
2224
})
25+
2326
const toSend = process.argv[3] === 'lob' ? base64 : 301
24-
const preRendered = JSON.stringify({data: toSend, error: null})
25-
const start = {
26-
http: () => {
27-
const http = require('http')
28-
http.createServer((req, res) => {
29-
res.setHeader('Content-Type', 'application/json; charset=utf-8')
30-
res.end(preRendered)
31-
}).listen(ports.http, () => logStart('http'))
32-
},
33-
fastify: () => {
34-
const fastify = require('fastify')()
35-
fastify.get('/bench/:id', function (req, reply) {
36-
reply.send({data: toSend, error: null})
37-
})
38-
fastify.listen(ports.fastify, () => logStart('fastify'))
39-
},
40-
polka: () => {
41-
const polka = require('polka')
42-
polka().get('/bench/:id', (req, res) => {
43-
res.setHeader('Content-Type', 'application/json; charset=utf-8')
44-
res.end(JSON.stringify({data: toSend, error: null}))
45-
}).listen(ports.polka, () => logStart('polka'))
46-
},
47-
scrud: () => {
48-
const scrudOpts = {port: ports.scrud, noCache: true, turbo: false}
49-
const scrud = require('scrud')
50-
scrud.register('bench', {read: (req, res) => scrud.sendData(res, toSend)})
51-
scrud.start(scrudOpts).then(() => logStart('scrud'))
52-
},
53-
express: () => {
54-
const express = require('express')
55-
express().get('/bench/:id', (req, res) => {
56-
res.json({data: toSend, error: null})
57-
}).listen(ports.express, () => logStart('express'))
58-
},
59-
hapi: () => {
60-
const { server: hapi } = require('hapi')
61-
let server = hapi({host: 'localhost', port: ports.hapi})
62-
server.route({
63-
method: 'GET',
64-
path: '/bench/{id}',
65-
handler: (request, h) => { return {data: toSend, error: null} }
66-
})
67-
server.start().then(() => logStart('hapi'))
68-
}
27+
28+
const preRendered = JSON.stringify({ data: toSend, error: null })
29+
30+
const start = {}
31+
32+
start.http = () => {
33+
const http = require('http')
34+
http.createServer((req, res) => {
35+
res.setHeader('Content-Type', 'application/json; charset=utf-8')
36+
res.end(preRendered)
37+
}).listen(ports.http, () => logStart('http'))
38+
}
39+
40+
start.fastify = () => {
41+
const fastify = require('fastify')()
42+
fastify.get('/bench/:id', function (req, reply) {
43+
reply.send({ data: toSend, error: null })
44+
})
45+
fastify.listen(ports.fastify, () => logStart('fastify'))
46+
}
47+
48+
start.polka = () => {
49+
const polka = require('polka')
50+
polka().get('/bench/:id', (req, res) => {
51+
res.setHeader('Content-Type', 'application/json; charset=utf-8')
52+
res.end(JSON.stringify({ data: toSend, error: null }))
53+
}).listen(ports.polka, () => logStart('polka'))
54+
}
55+
56+
start.scrud = () => {
57+
const scrudOpts = { port: ports.scrud, noCache: true, turbo: false }
58+
const scrud = require('scrud')
59+
scrud.register('bench', { read: (req, res) => scrud.sendData(res, toSend) })
60+
scrud.start(scrudOpts).then(() => logStart('scrud'))
61+
}
62+
63+
start.express = () => {
64+
const express = require('express')
65+
express().get('/bench/:id', (req, res) => {
66+
res.json({ data: toSend, error: null })
67+
}).listen(ports.express, () => logStart('express'))
68+
}
69+
70+
start.hapi = () => {
71+
const { server: hapi } = require('hapi')
72+
const server = hapi({ host: 'localhost', port: ports.hapi })
73+
server.route({
74+
method: 'GET',
75+
path: '/bench/{id}',
76+
handler: (request, h) => { return { data: toSend, error: null } }
77+
})
78+
server.start().then(() => logStart('hapi'))
6979
}
7080

7181
start[process.argv[2]]()

0 commit comments

Comments
 (0)