|
| 1 | +export class DebugStopwatch { |
| 2 | + public digits: number = 2; |
| 3 | + public name: string; |
| 4 | + #start: number; |
| 5 | + #end: number | null; |
| 6 | + public minLogTimeMs: number; |
| 7 | + |
| 8 | + public constructor(name: string, minLogTimeMs = 100) { |
| 9 | + this.name = name; |
| 10 | + this.#start = performance.now(); |
| 11 | + this.#end = null; |
| 12 | + this.minLogTimeMs = minLogTimeMs; |
| 13 | + } |
| 14 | + |
| 15 | + private log(str: string) { |
| 16 | + Logging.logDebug(`[${this.name}] [${this.toString()}] ${str}`); |
| 17 | + } |
| 18 | + |
| 19 | + public get duration(): number { |
| 20 | + return this.#end ? this.#end - this.#start : performance.now() - this.#start; |
| 21 | + } |
| 22 | + |
| 23 | + public get running(): boolean { |
| 24 | + return Boolean(!this.#end); |
| 25 | + } |
| 26 | + |
| 27 | + public restart(): this { |
| 28 | + this.#start = performance.now(); |
| 29 | + this.#end = null; |
| 30 | + return this; |
| 31 | + } |
| 32 | + |
| 33 | + public reset(): this { |
| 34 | + this.#start = performance.now(); |
| 35 | + this.#end = this.#start; |
| 36 | + return this; |
| 37 | + } |
| 38 | + |
| 39 | + public start(): this { |
| 40 | + if (!this.running) { |
| 41 | + this.#start = performance.now() - this.duration; |
| 42 | + this.#end = null; |
| 43 | + } |
| 44 | + |
| 45 | + return this; |
| 46 | + } |
| 47 | + |
| 48 | + public stop(text?: string): this { |
| 49 | + if (this.running) this.#end = performance.now(); |
| 50 | + if (text) { |
| 51 | + this.log(text); |
| 52 | + } |
| 53 | + return this; |
| 54 | + } |
| 55 | + |
| 56 | + private timeToString(time: number): string { |
| 57 | + if (time >= 1000) return `${(time / 1000).toFixed(this.digits)}s`; |
| 58 | + if (time >= 1) return `${time.toFixed(this.digits)}ms`; |
| 59 | + return `${(time * 1000).toFixed(this.digits)}μs`; |
| 60 | + } |
| 61 | + |
| 62 | + public toString(): string { |
| 63 | + return this.timeToString(this.duration); |
| 64 | + } |
| 65 | + |
| 66 | + public lastCheckpoint: number | null = null; |
| 67 | + public check(text?: string) { |
| 68 | + const checkTime = performance.now() - (this.lastCheckpoint ?? this.#start); |
| 69 | + this.lastCheckpoint = performance.now(); |
| 70 | + |
| 71 | + if (text) { |
| 72 | + if (checkTime < this.minLogTimeMs) { |
| 73 | + return; |
| 74 | + } |
| 75 | + const checkTimeStr = checkTime > 0 ? `${this.timeToString(checkTime)}` : ''; |
| 76 | + this.log(`${text} in ${checkTimeStr}`); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments