|
| 1 | +import { mean, roundTo2, stdDev } from "@monkeytype/util/numbers"; |
| 2 | + |
| 3 | +const timings = new Map<string, number[]>(); |
| 4 | + |
| 5 | +// Overloads for sync and async functions |
| 6 | +export function debugFunctionExecutionTime<T>( |
| 7 | + func: (...options: unknown[]) => T, |
| 8 | + funcName: string |
| 9 | +): T; |
| 10 | +export function debugFunctionExecutionTime<T>( |
| 11 | + func: (...options: unknown[]) => Promise<T>, |
| 12 | + funcName: string |
| 13 | +): Promise<T>; |
| 14 | +export function debugFunctionExecutionTime<T>( |
| 15 | + func: (...options: unknown[]) => T | Promise<T>, |
| 16 | + funcName: string |
| 17 | +): T | Promise<T> { |
| 18 | + const start = performance.now(); |
| 19 | + const ret = func(); |
| 20 | + |
| 21 | + // Check if the result is a Promise |
| 22 | + if (ret instanceof Promise) { |
| 23 | + // Handle async case |
| 24 | + return ret.then((resolvedValue) => { |
| 25 | + logTiming(start, funcName); |
| 26 | + return resolvedValue; |
| 27 | + }); |
| 28 | + } else { |
| 29 | + // Handle sync case |
| 30 | + logTiming(start, funcName); |
| 31 | + return ret; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function logTiming(start: number, funcName: string): void { |
| 36 | + const end = performance.now(); |
| 37 | + const time = end - start; |
| 38 | + |
| 39 | + if (!timings.has(funcName)) { |
| 40 | + timings.set(funcName, []); |
| 41 | + } |
| 42 | + |
| 43 | + const arr = timings.get(funcName) as number[]; |
| 44 | + arr.push(time); |
| 45 | + |
| 46 | + console.log(`${funcName} took ${roundTo2(time)} ms`); |
| 47 | + console.log(funcName, { |
| 48 | + average: `${roundTo2(mean(arr))} ms`, |
| 49 | + stdDev: `${roundTo2(stdDev(arr))} ms`, |
| 50 | + min: `${roundTo2(Math.min(...arr))} ms`, |
| 51 | + max: `${roundTo2(Math.max(...arr))} ms`, |
| 52 | + count: arr.length, |
| 53 | + }); |
| 54 | + const endOverhead = performance.now(); |
| 55 | + //@ts-expect-error chrome api thingy |
| 56 | + console.timeStamp(`#${arr.length} ${funcName}`, start, end, funcName); |
| 57 | + console.timeStamp( |
| 58 | + `#${arr.length} profiling overhead`, |
| 59 | + //@ts-expect-error chrome api thingy |
| 60 | + end, |
| 61 | + endOverhead, |
| 62 | + funcName |
| 63 | + ); |
| 64 | +} |
0 commit comments