util/lru: add a microbenchmark

The benchmark simulates an LRU being queries with uniformly random
inputs, in a set that's too large for the LRU, which should stress
the eviction codepath.

Signed-off-by: David Anderson <danderson@tailscale.com>
pull/9296/head
David Anderson 1 year ago committed by Dave Anderson
parent 18b2638b07
commit 472eb6f6f5

@ -3,7 +3,10 @@
package lru package lru
import "testing" import (
"math/rand"
"testing"
)
func TestLRU(t *testing.T) { func TestLRU(t *testing.T) {
var c Cache[int, string] var c Cache[int, string]
@ -40,3 +43,17 @@ func TestLRU(t *testing.T) {
t.Errorf("contains 3; should not") t.Errorf("contains 3; should not")
} }
} }
func BenchmarkLRU(b *testing.B) {
const lruSize = 10
const maxval = 15 // 33% more keys than the LRU can hold
c := Cache[int, bool]{MaxEntries: lruSize}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
k := rand.Intn(maxval)
if !c.Get(k) {
c.Set(k, true)
}
}
}

Loading…
Cancel
Save