Last active
April 6, 2022 13:14
-
-
Save fedeghe/f82c2a725c1ea7cc70ea1f37bda818e7 to your computer and use it in GitHub Desktop.
Quick benchmarking utility function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
// HOW TO USE IT | |
const test = require('./wherever/it/is/test') | |
function myFunc1 (a,b) { ... } | |
function myFunc2 (a,b) { ... } | |
const benchs = [{ | |
in: [[1,2,3.4], 'test'], | |
out: true | |
}, ...] | |
test( | |
benchs, | |
[myFunc1, myFunc2], | |
{iterations:1e3, stepDetail: false}// default | |
) | |
*/ | |
const formatX = (map, base) => (s, prec = 2) => { | |
if (s == 0) return `0 ${base}`; | |
let n = 0, nInt = 0; | |
for (let i in map) { | |
if (s >= map[i]) { | |
n = parseFloat((s / map[i]).toFixed(prec), 10); | |
nInt = parseInt(n, 10); | |
n = n == nInt ? nInt : n; | |
return `${n} ${i}`; | |
} | |
} | |
}, | |
formatSize = formatX({GB: 2 << 29, MB: 2 << 19, KB: 2 << 9, B: 1}, 'B'), | |
formatTime = formatX({m: 60e3, s: 1e3, ms: 1, µs: 1e-3, ns: 1e-6}, 'ms'); | |
module.exports = (bs, imp, options = {}) => { | |
const iterations = options.iterations || 1e3, | |
stepDetail = options.stepDetail || false, | |
impls = (imp.constructor.name === 'Array') ? imp : [imp], | |
globs = []; | |
impls.forEach(impl => { | |
const name = impl.name; | |
console.log(`› Testing \`${name}\``); | |
const out = {ok: 0, ko : 0}, | |
times = [], | |
sym = ['\u2717','\u2713' ], | |
upStart = + new Date(); | |
bs.forEach((b, i) => { | |
const start = +new Date(); | |
let j = 0, r; | |
while (j++ < iterations) r = impl(...b.in); | |
const end = +new Date(); | |
times[i] = end - start; | |
const spent = formatTime(times[i] / iterations); | |
if (JSON.stringify(r) === JSON.stringify(b.out)){ | |
stepDetail && console.log(`${sym[1]} test #${i+1} passed ${spent}`); | |
out.ok++; | |
} else { | |
if (stepDetail) { | |
console.log(`${sym[0]} test #${i+1} failed ${spent}`); | |
console.log('| expected:', b.out); | |
console.log('| received:', r); | |
console.log('\'+-------'); | |
} | |
out.ko++; | |
} | |
}) | |
var upEnd = + new Date(), | |
globTime = upEnd - upStart; | |
console.log(`Passed ${out.ok} | Failed ${out.ko}`); | |
console.log(`Total time ${formatTime(globTime, 1)}`); | |
if (!out.ko) { | |
globs.push({name, time : globTime}) | |
} | |
console.log(`Consuming ~${formatSize(process.memoryUsage().heapUsed)}`) | |
console.log('') | |
}) | |
if (globs.length > 1) { | |
console.log('∆ PODIUM') | |
globs.sort((a,b) => a.time - b.time).forEach((impl, i) => { | |
console.log(`${i+1}${['st','nd','rd',][i] || 'th'} place to ${impl.name} : ${formatTime(impl.time)}`) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment