|
| 1 | +import { |
| 2 | + calculateQuantiles, |
| 3 | + writeWalltimeResults, |
| 4 | + type Benchmark, |
| 5 | + type BenchmarkStats, |
| 6 | +} from "@codspeed/core"; |
| 7 | +import { BenchTaskResult, Suite, Task } from "vitest"; |
| 8 | +import { NodeBenchmarkRunner } from "vitest/runners"; |
| 9 | +import { patchRootSuiteWithFullFilePath } from "./common"; |
| 10 | + |
| 11 | +declare const __VERSION__: string; |
| 12 | + |
| 13 | +// Vitest's task result structure extends Tinybench with additional properties |
| 14 | +interface VitestTaskResult { |
| 15 | + state: "pass" | "fail" | "skip" | "todo"; |
| 16 | + startTime: number; |
| 17 | + duration?: number; |
| 18 | + benchmark?: BenchTaskResult; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * WalltimeRunner uses Vitest's default benchmark execution |
| 23 | + * and extracts results from the suite after completion |
| 24 | + */ |
| 25 | +export class WalltimeRunner extends NodeBenchmarkRunner { |
| 26 | + async runSuite(suite: Suite): Promise<void> { |
| 27 | + patchRootSuiteWithFullFilePath(suite); |
| 28 | + |
| 29 | + console.log( |
| 30 | + `[CodSpeed] running with @codspeed/vitest-plugin v${__VERSION__} (walltime mode)` |
| 31 | + ); |
| 32 | + |
| 33 | + // Let Vitest's default benchmark runner handle execution |
| 34 | + await super.runSuite(suite); |
| 35 | + |
| 36 | + // Extract benchmark results from the completed suite |
| 37 | + const benchmarks = await this.extractBenchmarkResults(suite); |
| 38 | + |
| 39 | + if (benchmarks.length > 0) { |
| 40 | + writeWalltimeResults(benchmarks); |
| 41 | + console.log( |
| 42 | + `[CodSpeed] Done collecting walltime data for ${benchmarks.length} benches.` |
| 43 | + ); |
| 44 | + } else { |
| 45 | + console.warn( |
| 46 | + `[CodSpeed] No benchmark results found after suite execution` |
| 47 | + ); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private async extractBenchmarkResults( |
| 52 | + suite: Suite, |
| 53 | + parentPath = "" |
| 54 | + ): Promise<Benchmark[]> { |
| 55 | + const benchmarks: Benchmark[] = []; |
| 56 | + const currentPath = parentPath |
| 57 | + ? `${parentPath}::${suite.name}` |
| 58 | + : suite.name; |
| 59 | + |
| 60 | + for (const task of suite.tasks) { |
| 61 | + if (task.meta?.benchmark && task.result?.state === "pass") { |
| 62 | + const benchmark = await this.processBenchmarkTask(task, currentPath); |
| 63 | + if (benchmark) { |
| 64 | + benchmarks.push(benchmark); |
| 65 | + } |
| 66 | + } else if (task.type === "suite") { |
| 67 | + const nestedBenchmarks = await this.extractBenchmarkResults( |
| 68 | + task, |
| 69 | + currentPath |
| 70 | + ); |
| 71 | + benchmarks.push(...nestedBenchmarks); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return benchmarks; |
| 76 | + } |
| 77 | + |
| 78 | + private async processBenchmarkTask( |
| 79 | + task: Task, |
| 80 | + suitePath: string |
| 81 | + ): Promise<Benchmark | null> { |
| 82 | + const uri = `${suitePath}::${task.name}`; |
| 83 | + |
| 84 | + const result = task.result; |
| 85 | + if (!result) { |
| 86 | + console.warn(` ⚠ No result data available for ${uri}`); |
| 87 | + return null; |
| 88 | + } |
| 89 | + |
| 90 | + try { |
| 91 | + const stats = this.convertVitestResultToBenchmarkStats( |
| 92 | + result as VitestTaskResult |
| 93 | + ); |
| 94 | + |
| 95 | + if (stats === null) { |
| 96 | + console.log(` ✔ No walltime data to collect for ${uri}`); |
| 97 | + return null; |
| 98 | + } |
| 99 | + |
| 100 | + const coreBenchmark: Benchmark = { |
| 101 | + name: task.name, |
| 102 | + uri, |
| 103 | + config: { |
| 104 | + warmup_time_ns: null, // Vitest doesn't expose this in task.result |
| 105 | + min_round_time_ns: null, // Vitest doesn't expose this in task.result |
| 106 | + }, |
| 107 | + stats, |
| 108 | + }; |
| 109 | + |
| 110 | + console.log(` ✔ Collected walltime data for ${uri}`); |
| 111 | + return coreBenchmark; |
| 112 | + } catch (error) { |
| 113 | + console.warn( |
| 114 | + ` ⚠ Failed to process benchmark result for ${uri}:`, |
| 115 | + error |
| 116 | + ); |
| 117 | + return null; |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + private convertVitestResultToBenchmarkStats( |
| 122 | + result: VitestTaskResult |
| 123 | + ): BenchmarkStats | null { |
| 124 | + const benchmark = result.benchmark; |
| 125 | + |
| 126 | + if (!benchmark) { |
| 127 | + throw new Error("No benchmark data available in result"); |
| 128 | + } |
| 129 | + |
| 130 | + // All tinybench times are in milliseconds, convert to nanoseconds |
| 131 | + const ms_to_ns = (ms: number) => ms * 1_000_000; |
| 132 | + |
| 133 | + const { totalTime, min, max, mean, sd, samples } = benchmark; |
| 134 | + |
| 135 | + // Get individual sample times in nanoseconds and sort them |
| 136 | + const sortedTimesNs = samples.map(ms_to_ns).sort((a, b) => a - b); |
| 137 | + const meanNs = ms_to_ns(mean); |
| 138 | + const stdevNs = ms_to_ns(sd); |
| 139 | + |
| 140 | + if (sortedTimesNs.length == 0) { |
| 141 | + // Sometimes the benchmarks can be completely optimized out and not even run, but its beforeEach and afterEach hooks are still executed, and the task is still considered a success. |
| 142 | + // This is the case for the hooks.bench.ts example in this package |
| 143 | + return null; |
| 144 | + } |
| 145 | + |
| 146 | + const { |
| 147 | + q1_ns, |
| 148 | + q3_ns, |
| 149 | + median_ns, |
| 150 | + iqr_outlier_rounds, |
| 151 | + stdev_outlier_rounds, |
| 152 | + } = calculateQuantiles({ meanNs, stdevNs, sortedTimesNs }); |
| 153 | + |
| 154 | + return { |
| 155 | + min_ns: ms_to_ns(min), |
| 156 | + max_ns: ms_to_ns(max), |
| 157 | + mean_ns: meanNs, |
| 158 | + stdev_ns: stdevNs, |
| 159 | + q1_ns, |
| 160 | + median_ns, |
| 161 | + q3_ns, |
| 162 | + total_time: totalTime / 1_000, // convert from ms to seconds |
| 163 | + iter_per_round: sortedTimesNs.length, |
| 164 | + rounds: 1, // Tinybench only runs one round |
| 165 | + iqr_outlier_rounds, |
| 166 | + stdev_outlier_rounds, |
| 167 | + warmup_iters: 0, // TODO: get warmup iters here |
| 168 | + }; |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +export default WalltimeRunner; |
0 commit comments