Skip to content

Commit

Permalink
Use AllocsPerRun
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Feb 4, 2023
1 parent 563cb0a commit 82fc467
Showing 1 changed file with 5 additions and 28 deletions.
33 changes: 5 additions & 28 deletions p2p/host/resource-manager/obs/stats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package obs

import (
"math/rand"
"runtime"
"sync"
"testing"
"time"
Expand Down Expand Up @@ -115,48 +114,26 @@ func BenchmarkMetricsRecording(b *testing.B) {
}
}

func noop() {
runtime.Gosched()
}

func TestNoAllocs(t *testing.T) {
str, err := NewStatsTraceReporter()
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

evtCount := 10_000
evts := make([]rcmgr.TraceEvt, evtCount)
evts := make([]rcmgr.TraceEvt, 0, evtCount)
rng := rand.New(rand.NewSource(1))

for i := 0; i < evtCount; i++ {
evts[i] = randomTraceEvt(rng)
evts = append(evts, randomTraceEvt(rng))
}

failures := 0

tagSlice := make([]string, 0, 10)
_ = tagSlice
_ = str

allocs := testing.AllocsPerRun(100, func() {
for i := 0; i < evtCount; i++ {
noop()
str.consumeEventWithLabelSlice(evts[i], &tagSlice)
}
})

if allocs > 10 {
failures++
}

if failures > 0 {
t.Fatalf("expected less than 10 heap bytes")
}

// To prevent the GC from collecting our fake events.
unused := 0
for i := 0; i < evtCount; i++ {
unused += int(evts[i].Delta)
t.Fatalf("expected less than 10 heap bytes, got %f", allocs)
}
require.GreaterOrEqual(t, unused, 0)
}

0 comments on commit 82fc467

Please sign in to comment.