Skip to content

Commit

Permalink
bench: add websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx committed Aug 22, 2024
1 parent 69cfd97 commit 1444870
Show file tree
Hide file tree
Showing 9 changed files with 849 additions and 1 deletion.
124 changes: 124 additions & 0 deletions benchmarks/_util/runner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// @ts-check

'use strict'

class Info {
/** @type {string} */
#name
/** @type {bigint} */
#current
/** @type {bigint} */
#finish
/** @type {(...args: any[]) => any} */
#callback
/** @type {boolean} */
#finalized = false

/**
* @param {string} name
* @param {(...args: any[]) => any} callback
*/
constructor (name, callback) {
this.#name = name
this.#callback = callback
}

get name () {
return this.#name
}

start () {
if (this.#finalized) {
throw new TypeError('called after finished.')
}
this.#current = process.hrtime.bigint()
}

end () {
if (this.#finalized) {
throw new TypeError('called after finished.')
}
this.#finish = process.hrtime.bigint()
this.#finalized = true
this.#callback()
}

diff () {
return Number(this.#finish - this.#current)
}
}

/**
* @typedef BenchMarkHandler
* @type {(ev: { name: string; start(): void; end(): void; }) => any}
*/

/**
* @param {Record<string, BenchMarkHandler>} experiments
* @param {{}} [options]
* @returns {Promise<{ name: string; average: number; samples: number; fn: BenchMarkHandler; min: number; max: number }[]>}
*/
async function bench (experiments, options = {}) {
const names = Object.keys(experiments)

/** @type {{ name: string; average: number; samples: number; fn: BenchMarkHandler; min: number; max: number }[]} */
const results = []

async function waitMaybePromiseLike (p) {
if (
(typeof p === 'object' || typeof p === 'function') &&
p !== null &&
typeof p.then === 'function'
) {
await p
}
}

for (let i = 0; i < names.length; ++i) {
const name = names[i]
const fn = experiments[name]
const samples = []

let timing = 0

for (let j = 0; j < 128 || timing < 800_000_000; ++j) {
let resolve = (value) => {}
let reject = (reason) => {}
const promise = new Promise(
(_resolve, _reject) => { resolve = _resolve; reject = _reject }
)

const info = new Info(name, resolve)

try {
const p = fn(info)

await waitMaybePromiseLike(p)
} catch (err) {
reject(err)
}

await promise

samples.push({ time: info.diff() })

timing += info.diff()
}

const average =
samples.map((v) => v.time).reduce((a, b) => a + b, 0) / samples.length

results.push({
name: names[i],
average,
samples: samples.length,
fn,
min: samples.reduce((a, acc) => Math.min(a, acc.time), samples[0].time),
max: samples.reduce((a, acc) => Math.max(a, acc.time), samples[0].time)
})
}

return results
}

module.exports = { bench }
Loading

0 comments on commit 1444870

Please sign in to comment.