import { performance } from "node:perf_hooks"; import { assertBenchmarkResult, median, type BenchmarkProfile, type BenchmarkResult, } from "./benchmark-result.ts"; /** * Spec ยง49. Repeated samples with a median, so one noisy scheduler slice can * neither fail a linear implementation nor hide a slow one. * * `run` either does the work (and is timed here) or returns a duration it * measured itself, which lets tests inject exact durations. */ export type BenchmarkOptions = Readonly<{ samples: number; warmup?: number; profile?: BenchmarkProfile; cardinality?: number; metadata?: Readonly>; measureHeap?: boolean; run: () => unknown; }>; function heapUsed(): number { return process.memoryUsage().heapUsed; } export async function benchmark( name: string, options: BenchmarkOptions, ): Promise { if (!Number.isSafeInteger(options.samples) || options.samples < 1) { throw new TypeError("benchmark samples must be a positive integer"); } for (let index = 0; index < (options.warmup ?? 0); index += 1) { await options.run(); } const samples: number[] = []; let peakHeapDelta = 0; for (let index = 0; index < options.samples; index += 1) { const heapBefore = options.measureHeap ? heapUsed() : 0; const startedAt = performance.now(); const reported = await options.run(); const elapsed = performance.now() - startedAt; if (options.measureHeap) { peakHeapDelta = Math.max(peakHeapDelta, heapUsed() - heapBefore); } samples.push(typeof reported === "number" && Number.isFinite(reported) ? reported : elapsed); } return assertBenchmarkResult( Object.freeze({ name, profile: options.profile ?? "S0", cardinality: options.cardinality ?? 0, samples: Object.freeze(samples), medianMs: median(samples), ...(options.measureHeap ? { heapBytes: Math.max(0, peakHeapDelta) } : {}), metadata: Object.freeze({ ...(options.metadata ?? {}) }), }), ); }