Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Created June 30, 2020 10:22
Show Gist options
  • Save tadeaspetak/65d628e524c2d7b971bb4141feb466b7 to your computer and use it in GitHub Desktop.
Save tadeaspetak/65d628e524c2d7b971bb4141feb466b7 to your computer and use it in GitHub Desktop.
Simple js profiler.
class Timer {
start: number;
constructor() {
this.start = performance.now();
}
elapsed() {
return performance.now() - this.start;
}
}
export class Profiler {
timers: Map<string, Timer> = new Map();
totals: Map<string, Array<number>> = new Map();
start(name: string) {
if (this.timers.has(name)) {
throw Error(`Timer ${name} already exists.`);
}
this.timers.set(name, new Timer());
}
stop(name: string) {
const timer = this.timers.get(name);
if (!timer) {
throw Error(`Timer ${name} does not exist.`);
}
this.totals.set(name, [...(this.totals.get(name) || []), timer.elapsed()]);
this.timers.delete(name);
}
print() {
this.totals.forEach((value, key) => {
// eslint-disable-next-line no-console
console.log({
name: key,
count: value.length,
time: value.reduce((a, b) => a + b, 0),
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment