Files
tailscale/tstest/allocs.go
Brad Fitzpatrick 3ccc7725a3 tstest, util/testenv: drop tstest's dependency on the testing package
Change tstest's exported functions (AssertNotParallel, Replace,
Parallel, RequireRoot, SkipOnKernelVersions, MinAllocsPerRun, FixLogs,
UnfixLogs, CheckIsZero, ResourceCheck) to take testenv.TB instead of
testing.TB or *testing.T, so importing tstest from non-test code no
longer links the testing package and its flag registration side
effects into the binary. Add testenv.Verbose to replace the one use of
testing.Verbose, and a deptest check to keep testing out of tstest's
dependency graph.

Callers are unaffected: *testing.T and testing.TB both satisfy
testenv.TB.

Updates tailscale/corp#45223

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: Ib373ff66ceff638d071582baf8367245987e9155
2026-07-21 13:03:23 -07:00

52 lines
1.3 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package tstest
import (
"fmt"
"runtime"
"time"
"tailscale.com/util/testenv"
)
// MinAllocsPerRun asserts that f can run with no more than target allocations.
// It runs f up to 1000 times or 5s, whichever happens first.
// If f has executed more than target allocations on every run, it returns a non-nil error.
//
// MinAllocsPerRun sets GOMAXPROCS to 1 during its measurement and restores
// it before returning.
func MinAllocsPerRun(t testenv.TB, target uint64, f func()) error {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
var memstats runtime.MemStats
var min, max, sum uint64
start := time.Now()
var iters int
for {
runtime.ReadMemStats(&memstats)
startMallocs := memstats.Mallocs
f()
runtime.ReadMemStats(&memstats)
mallocs := memstats.Mallocs - startMallocs
// TODO: if mallocs < target, return an error? See discussion in #3204.
if mallocs <= target {
return nil
}
if min == 0 || mallocs < min {
min = mallocs
}
if mallocs > max {
max = mallocs
}
sum += mallocs
iters++
if iters == 1000 || time.Since(start) > 5*time.Second {
break
}
}
return fmt.Errorf("min allocs = %d, max allocs = %d, avg allocs/run = %f, want run with <= %d allocs", min, max, float64(sum)/float64(iters), target)
}