Skip to content

Instantly share code, notes, and snippets.

@zodman
Created May 9, 2024 14:36
Show Gist options
  • Save zodman/ed8891bac42bbc886feb48c3fcc16ae6 to your computer and use it in GitHub Desktop.
Save zodman/ed8891bac42bbc886feb48c3fcc16ae6 to your computer and use it in GitHub Desktop.
/* eslint-disable @typescript-eslint/ban-types */
// @ts-nocheck
/**
* Use to patch all functions/methods in a class and make them print out run time
* in ms to the console.
*
* This decorator will only patch functions declared in the target class.
* It will **not** patch functions reside in the **base class**.
* Dynamically created functions or functions received from the outside as input
* may also not be patched.
*
* Keep in mind that the act of printing stuffs to the console itself will slow down
* some function a little. This could add up if that function is called multiple times in a loop.
* Callbacks may also not be tracked so functions that rely on
* callbacks to do heavy lifting may appear to take very little time
* here.
*
* @param threshold allow filtering log to only those that took more than the threshold (in ms)
*/
export function ProfileClassToConsole({
prefix = '[ProfileClassToConsole]',
threshold = 1000,
} = {}) {
return function (target: any) {
// Guard to skip patching
// if (!isDevMode()) {
// return;
//
// Loop through all property of the class
for (const propName of Object.getOwnPropertyNames(target.prototype)) {
const descriptor = Object.getOwnPropertyDescriptor(
target.prototype,
propName,
);
// If not a function, skip
if (!(descriptor.value instanceof Function)) {
continue;
}
const windowsPerfomance = window.performance;
const fn = descriptor.value;
descriptor.value = function (...args: any[]): any {
const before = windowsPerfomance.now();
const result = fn.apply(this, args);
const after = windowsPerfomance.now();
const runTime = after - before;
if (runTime > threshold) {
console.info(
prefix,
target.name,
': ',
propName,
'took',
runTime,
'ms',
);
}
return result;
};
Object.defineProperty(target.prototype, propName, descriptor);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment