Skip to content

Instantly share code, notes, and snippets.

@loucadufault
Created October 26, 2022 07:52
Show Gist options
  • Save loucadufault/b115e6f4c06a664c1aa395f26e6aeb6a to your computer and use it in GitHub Desktop.
Save loucadufault/b115e6f4c06a664c1aa395f26e6aeb6a to your computer and use it in GitHub Desktop.
TypeScript timer/timing utilities for conveniently profiling code, for example to record the time taken by various function sections
export class Timer {
private static nextTimerIndex = 0;
public readonly timerIndex;
private startTime: number | undefined;
private endTime: number | undefined;
constructor(startOnInit: boolean = false) {
this.timerIndex = Timer.nextTimerIndex++;
if (startOnInit) this.start();
}
private static getCurrentTime() {
return Date.now();
}
start() {
if (this.startTime !== undefined) {
throw new Error("Timer has already been started");
}
this.startTime = Timer.getCurrentTime();
}
stop() {
if (this.startTime === undefined) {
throw new Error("Timer has not yet been started");
} // intentionally silent on repeat stops
this.endTime = Timer.getCurrentTime();
}
getRecordedTime() {
if (this.startTime == undefined || this.endTime === undefined) {
throw new Error("Timer has not recorded a time");
}
return this.endTime - this.startTime;
}
}
export class TimerGroup {
private readonly timers: Map<string, Timer> = new Map();
registerTimer(timerName: string) {
this.timers.set(timerName, new Timer(false));
}
startTimer(timerName: string) {
if (this.timers.has(timerName)) {
this.timers.get(timerName)!.start();
} else {
this.timers.set(timerName, new Timer(true));
}
}
stopTimer(timerName: string) {
if (this.timers.has(timerName)) {
this.timers.get(timerName)!.stop();
} // silent
}
stopAllTimers() {
this.timers.forEach(timer => timer.stop());
}
summarize() { // console.log return value of this for quick summary of timers
Array.from(this.timers.keys()).forEach(timerName => {
const timer = this.timers.get(timerName)!;
return `${timerName} (${timer.timerIndex}): ${timer.getRecordedTime()}ms`;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment