|
| 1 | +import { performance } from 'perf_hooks'; |
| 2 | + |
| 3 | +/** Number of decimal places to keep in timers */ |
| 4 | +const TruncateTimers = 4; |
| 5 | +/** |
| 6 | + * Utility to record some metrics about the execution of the function |
| 7 | + * |
| 8 | + * TODO this should be replaced by open telemetry |
| 9 | + */ |
| 10 | +export class Metrics { |
| 11 | + /** |
| 12 | + * Start time of all timers |
| 13 | + */ |
| 14 | + timers: Map<string, { start: number; duration?: number }> = new Map(); |
| 15 | + |
| 16 | + getTime(): number { |
| 17 | + return performance.now(); |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Start a timer at the current time |
| 22 | + * @param timeName name of timer to start |
| 23 | + */ |
| 24 | + public start(timeName: string): void { |
| 25 | + const existing = this.timers.get(timeName); |
| 26 | + if (existing != null && existing.duration == null) { |
| 27 | + throw new Error(`Duplicate startTime for "${timeName}"`); |
| 28 | + } |
| 29 | + this.timers.set(timeName, { start: this.getTime() }); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * End the timer, returning the duration in milliseconds |
| 34 | + * @param timeName timer to end |
| 35 | + */ |
| 36 | + public end(timeName: string): number { |
| 37 | + const timer = this.timers.get(timeName); |
| 38 | + if (timer == null) throw new Error(`Missing startTime information for "${timeName}"`); |
| 39 | + const duration = this.getTime() - timer.start; |
| 40 | + timer.duration = Number(duration.toFixed(TruncateTimers)); |
| 41 | + return duration; |
| 42 | + } |
| 43 | + |
| 44 | + /** Get list of all timers that have run */ |
| 45 | + public get metrics(): Record<string, number> | undefined { |
| 46 | + if (this.timers.size === 0) return undefined; |
| 47 | + const output: Record<string, number> = {}; |
| 48 | + for (const [key, timer] of this.timers.entries()) { |
| 49 | + if (timer.duration != null) output[key] = timer.duration; |
| 50 | + } |
| 51 | + return output; |
| 52 | + } |
| 53 | + |
| 54 | + /** Get a list of timers that never finished */ |
| 55 | + public get unfinished(): string[] | undefined { |
| 56 | + const st: string[] = []; |
| 57 | + for (const [key, timer] of this.timers.entries()) { |
| 58 | + if (timer.duration == null) st.push(key); |
| 59 | + } |
| 60 | + if (st.length === 0) return undefined; |
| 61 | + return st; |
| 62 | + } |
| 63 | +} |
0 commit comments