Skip to content

Instantly share code, notes, and snippets.

@cphoover
Created December 19, 2018 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cphoover/53b727100457855d21997a1ff8126a99 to your computer and use it in GitHub Desktop.
Save cphoover/53b727100457855d21997a1ff8126a99 to your computer and use it in GitHub Desktop.
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