From e14443b9c3fcd119813ef1ac109404a063b7dee5 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 17 Mar 2026 01:50:36 -1000 Subject: [PATCH] Fix ProtoSize_Varint benchmarks: prevent constant folding The compiler constant-folds ProtoSize::varint(42) to 1 and optimizes the entire inner loop to a single addition, causing ~62ns jitter-dominated measurements. Use varying inputs (i & 0x7F for small, 0xFFFF0000 | i for large) so each call computes a real result. --- tests/benchmarks/components/api/bench_proto_varint.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/benchmarks/components/api/bench_proto_varint.cpp b/tests/benchmarks/components/api/bench_proto_varint.cpp index ff4a656980..0b5ccc2b7d 100644 --- a/tests/benchmarks/components/api/bench_proto_varint.cpp +++ b/tests/benchmarks/components/api/bench_proto_varint.cpp @@ -104,10 +104,12 @@ BENCHMARK(Encode_Varint_MaxUint32); // --- ProtoSize::varint() benchmarks --- static void ProtoSize_Varint_Small(benchmark::State &state) { + // Use varying input to prevent constant folding. + // Values 0-127 all take 1 byte but the compiler can't prove that. for (auto _ : state) { uint32_t result = 0; for (int i = 0; i < kInnerIterations; i++) { - result += ProtoSize::varint(42); + result += ProtoSize::varint(static_cast(i) & 0x7F); } benchmark::DoNotOptimize(result); } @@ -116,10 +118,11 @@ static void ProtoSize_Varint_Small(benchmark::State &state) { BENCHMARK(ProtoSize_Varint_Small); static void ProtoSize_Varint_Large(benchmark::State &state) { + // Use varying input to prevent constant folding. for (auto _ : state) { uint32_t result = 0; for (int i = 0; i < kInnerIterations; i++) { - result += ProtoSize::varint(0xFFFFFFFF); + result += ProtoSize::varint(0xFFFF0000 | static_cast(i)); } benchmark::DoNotOptimize(result); }