| 1 |
package sturdyc_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"testing" |
| 5 |
"time" |
| 6 |
|
| 7 |
"github.com/viccon/sturdyc" |
| 8 |
) |
| 9 |
|
| 10 |
type benchmarkMetric[T any] struct { |
| 11 |
getOps int |
| 12 |
setOps int |
| 13 |
hits int |
| 14 |
evictions int |
| 15 |
} |
| 16 |
|
| 17 |
func (b *benchmarkMetric[T]) recordGet(c *sturdyc.Client[T], key string) { |
| 18 |
b.getOps++ |
| 19 |
_, ok := c.Get(key) |
| 20 |
if ok { |
| 21 |
b.hits++ |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
func (b *benchmarkMetric[T]) recordSet(c *sturdyc.Client[T], key string, value T) { |
| 26 |
b.setOps++ |
| 27 |
evict := c.Set(key, value) |
| 28 |
if evict { |
| 29 |
b.evictions++ |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
type benchmarkMetrics[T any] []benchmarkMetric[T] |
| 34 |
|
| 35 |
func (metrics benchmarkMetrics[T]) hitRate() (float64, string) { |
| 36 |
var ops, hits int |
| 37 |
for _, metrics := range metrics { |
| 38 |
ops += metrics.getOps |
| 39 |
hits += metrics.hits |
| 40 |
} |
| 41 |
return float64(hits) / float64(ops), "hits/op" |
| 42 |
} |
| 43 |
|
| 44 |
func (metrics benchmarkMetrics[T]) evictions() (float64, string) { |
| 45 |
var ops, evictions int |
| 46 |
for _, metrics := range metrics { |
| 47 |
ops += metrics.setOps |
| 48 |
evictions += metrics.evictions |
| 49 |
} |
| 50 |
return float64(evictions) / float64(ops), "evictions/op" |
| 51 |
} |
| 52 |
|
| 53 |
func BenchmarkGetConcurrent(b *testing.B) { |
| 54 |
cacheKey := "key" |
| 55 |
capacity := 1_000_000 |
| 56 |
numShards := 100 |
| 57 |
ttl := time.Hour |
| 58 |
evictionPercentage := 5 |
| 59 |
c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 60 |
sturdyc.WithNoContinuousEvictions(), |
| 61 |
) |
| 62 |
c.Set(cacheKey, "value") |
| 63 |
|
| 64 |
metrics := make(benchmarkMetrics[string], 0) |
| 65 |
b.ResetTimer() |
| 66 |
b.RunParallel(func(pb *testing.PB) { |
| 67 |
var metric benchmarkMetric[string] |
| 68 |
for pb.Next() { |
| 69 |
metric.recordGet(c, cacheKey) |
| 70 |
} |
| 71 |
metrics = append(metrics, metric) |
| 72 |
}) |
| 73 |
b.StopTimer() |
| 74 |
b.ReportMetric(metrics.hitRate()) |
| 75 |
} |
| 76 |
|
| 77 |
func BenchmarkSetConcurrent(b *testing.B) { |
| 78 |
capacity := 10_000_000 |
| 79 |
numShards := 10_000 |
| 80 |
ttl := time.Hour |
| 81 |
evictionPercentage := 5 |
| 82 |
c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 83 |
sturdyc.WithNoContinuousEvictions(), |
| 84 |
) |
| 85 |
|
| 86 |
metrics := make(benchmarkMetrics[string], 0) |
| 87 |
b.ResetTimer() |
| 88 |
b.RunParallel(func(pb *testing.PB) { |
| 89 |
var metric benchmarkMetric[string] |
| 90 |
for pb.Next() { |
| 91 |
// NOTE: The benchmark includes the time for generating random keys. |
| 92 |
key := randKey(16) |
| 93 |
metric.recordSet(c, key, "value") |
| 94 |
} |
| 95 |
metrics = append(metrics, metric) |
| 96 |
}) |
| 97 |
b.StopTimer() |
| 98 |
b.ReportMetric(metrics.evictions()) |
| 99 |
} |