diff --git a/internal/agent/alma_seen_test.go b/internal/agent/alma_seen_test.go index a351ff0f5..34a91d7ec 100644 --- a/internal/agent/alma_seen_test.go +++ b/internal/agent/alma_seen_test.go @@ -46,7 +46,7 @@ func TestAlmaProvidersSeenDecodeOnce(t *testing.T) { if err != nil || len(ps) != 1 || ps[0].Name != "magpie" || len(ps[0].Known) != 400 || ps[0].Models[0] != "gpt-5.4" { t.Fatalf("first look: %v %+v", err, ps) } - if n := testing.AllocsPerRun(20, func() { + if n := leastAllocs(20, func() { if ps, err := almaProvidersSeen(); err != nil || len(ps) != 1 { t.Fatal(err, ps) } @@ -59,7 +59,7 @@ func TestAlmaProvidersSeenDecodeOnce(t *testing.T) { // the same answer asked for again, past the time one is kept, is not // decoded again either almaReadFor = 0 - if n := testing.AllocsPerRun(5, func() { + if n := leastAllocs(5, func() { if ps, err := almaProvidersSeen(); err != nil || len(ps) != 1 { t.Fatal(err, ps) } diff --git a/internal/agent/least_allocs_test.go b/internal/agent/least_allocs_test.go new file mode 100644 index 000000000..f014c4863 --- /dev/null +++ b/internal/agent/least_allocs_test.go @@ -0,0 +1,35 @@ +package agent + +import ( + "runtime" + "testing" +) + +// leastAllocs is testing.AllocsPerRun's fewest over five rounds: it counts +// every goroutine's allocations, and another test's left running (a +// watcher, a poll) lands in one round now and then, never in all five. +func leastAllocs(runs int, f func()) float64 { + least := testing.AllocsPerRun(runs, f) + for range 4 { + least = min(least, testing.AllocsPerRun(runs, f)) + } + return least +} + +// leastBytes is the fewest bytes a run of f allocated, over five rounds of +// runs, for the reason leastAllocs gives. +func leastBytes(runs int, f func()) uint64 { + var least uint64 + for i := range 5 { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for range runs { + f() + } + runtime.ReadMemStats(&after) + if n := (after.TotalAlloc - before.TotalAlloc) / uint64(runs); i == 0 || n < least { + least = n + } + } + return least +}