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>
This commit is contained in:
David Anderson 2023-09-07 09:31:33 -07:00 committed by Dave Anderson
parent 18b2638b07
commit 472eb6f6f5

View File

@ -3,7 +3,10 @@
package lru
import "testing"
import (
"math/rand"
"testing"
)
func TestLRU(t *testing.T) {
var c Cache[int, string]
@ -40,3 +43,17 @@ func TestLRU(t *testing.T) {
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)
}
}
}