/** * @module perf-timer * * Lightweight, high-resolution performance timer utility for ibgib operations. * Activated conditionally when VCS_PERF=1 or IBGIB_PERF=1 in the environment. */ export interface PerfTimer { label: string; startMs: number; /** Returns elapsed milliseconds without logging */ elapsedMs: () => number; /** Logs a named intermediate checkpoint and returns split time in ms */ mark: (stepLabel: string) => number; /** Logs final duration and returns total elapsed milliseconds */ stop: (detail?: string) => number; } /** * Returns true if performance benchmarking is activated via environment flags. */ export function isPerfEnabled(): boolean { if (typeof process === 'undefined' || !process.env) { return false; } return process.env.VCS_PERF === '1' || process.env.IBGIB_PERF === '1'; } function nowMs(): number { if (typeof globalThis !== 'undefined' && globalThis.performance?.now) { return globalThis.performance.now(); } return Date.now(); } /** * Creates and starts a high-resolution performance timer. * If telemetry is disabled, returns zero-overhead no-op functions. * * @param label Descriptive identifier for the timed operation (e.g. `[cli][merge]`, `[sync][delta]`) * @param forceEnabled Optional override to force timer output regardless of env vars */ export function startPerfTimer(label: string, forceEnabled?: boolean): PerfTimer { const enabled = forceEnabled ?? isPerfEnabled(); const startMs = nowMs(); let lastMarkMs = startMs; if (!enabled) { return { label, startMs, elapsedMs: () => 0, mark: () => 0, stop: () => 0, }; } return { label, startMs, elapsedMs: () => nowMs() - startMs, mark: (stepLabel: string) => { const current = nowMs(); const splitMs = current - lastMarkMs; lastMarkMs = current; console.log(`[PERF]${label} ├─ ${stepLabel}: ${splitMs.toFixed(1)}ms`); return splitMs; }, stop: (detail?: string) => { const totalMs = nowMs() - startMs; const suffix = detail ? ` (${detail})` : ''; console.log(`[PERF]${label} └─ total: ${totalMs.toFixed(1)}ms${suffix}`); return totalMs; }, }; }