Created
December 19, 2018 21:31
-
-
Save cphoover/53b727100457855d21997a1ff8126a99 to your computer and use it in GitHub Desktop.
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
const benchmarksMap = {}; | |
// benchmarks an individual fn | |
export const benchmarkFn = (id, fn) => { | |
// if id is not a string throw TypeError | |
if ("string" !== typeof id) throw new TypeError("id should be a string"); | |
// if obj is not an object throw an error | |
if ("function" !== typeof fn) throw new TypeError("fn should be a function"); | |
return (...args) => { | |
const start = performance.now(); | |
const res = fn(...args); | |
const end = performance.now(); | |
const delta = end - start; | |
if (!benchmarksMap[id]) { | |
benchmarksMap[id] = { | |
name: id, | |
runs: 1, | |
avgTime: delta, | |
total: delta | |
}; | |
} else { | |
benchmarksMap[id].runs += 1; | |
benchmarksMap[id].avgTime = (benchmarksMap[id].avgTime + delta) / 2; | |
benchmarksMap[id].total += delta; | |
} | |
return res; | |
}; | |
}; | |
// benchmark all non-class (no-prototype) fns of an object | |
export const benchmarkAllFns = (id, obj) => { | |
// if id is not a string throw TypeError | |
if ("string" !== typeof id) throw new TypeError("id should be a string"); | |
// if obj is not an object throw an error | |
if ("object" !== typeof obj) throw new TypeError("obj should be an object"); | |
const keys = Object.getOwnPropertyNames(obj); | |
for (const key of keys) { | |
console.log(typeof obj[key] === 'function' && !obj[key].prototype) | |
if (typeof obj[key] === 'function') { | |
obj[key] = benchmarkFn(`${id}-${key}`, obj[key]); | |
} | |
} | |
} | |
// prints a table with benchmark values | |
export const showBenchmarks = () => { | |
console.log(Object.values(benchmarksMap)); | |
console.table(Object.values(benchmarksMap)); | |
}; | |
window.showBenchmarks = showBenchmarks; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment