Debian Codegraph @

sieve_bench_custom_test.go

raw
1 // sieve_bench_custom_test.go - benchmarks for Sieve cache with custom memory allocator
2 //
3 // (c) 2024 Sudhi Herle <[email protected]>
4 //
5 // Copyright 2024- Sudhi Herle <sw-at-herle-dot-net>
6 // License: BSD-2-Clause
7
8 package sieve_test
9
10 import (
11 "fmt"
12 "math/rand"
13 "runtime"
14 "runtime/debug"
15 "testing"
16 "time"
17
18 "github.com/opencoff/go-sieve"
19 )
20
21 // BenchmarkSieveAdd benchmarks the Add operation
22 func BenchmarkSieveAdd(b *testing.B) {
23 // Test with various cache sizes
24 for _, cacheSize := range []int{1024, 8192, 32768} {
25 b.Run(fmt.Sprintf("CacheSize_%d", cacheSize), func(b *testing.B) {
26 cache := sieve.Must(sieve.New[int, int](cacheSize))
27
28 // Generate keys with some predictable access pattern
29 keys := make([]int, b.N)
30 for i := 0; i < b.N; i++ {
31 if i%3 == 0 {
32 // Reuse some keys for cache hits
33 keys[i] = i % (cacheSize / 2)
34 } else {
35 // Use new keys for cache misses
36 keys[i] = i + cacheSize
37 }
38 }
39
40 b.ResetTimer()
41
42 // Perform add operations that will cause evictions
43 for i := 0; i < b.N; i++ {
44 key := keys[i]
45 cache.Add(key, key)
46
47 // Occasionally delete some items to test the node recycling
48 if i%5 == 0 && i > 0 {
49 cache.Delete(keys[i-1])
50 }
51 }
52 })
53 }
54 }
55
56 // BenchmarkSieveGetHitMiss benchmarks Get operations with a mix of hits and misses
57 func BenchmarkSieveGetHitMiss(b *testing.B) {
58 cacheSize := 8192
59 cache := sieve.Must(sieve.New[int, int](cacheSize))
60
61 // Fill the cache with initial data
62 for i := 0; i < cacheSize; i++ {
63 cache.Add(i, i)
64 }
65
66 // Generate a mix of hit and miss patterns
67 keys := make([]int, b.N)
68 for i := 0; i < b.N; i++ {
69 if i%2 == 0 {
70 // Cache hit
71 keys[i] = rand.Intn(cacheSize)
72 } else {
73 // Cache miss
74 keys[i] = cacheSize + rand.Intn(cacheSize)
75 }
76 }
77
78 b.ResetTimer()
79
80 // Perform get operations
81 var hit, miss int
82 for i := 0; i < b.N; i++ {
83 key := keys[i]
84 if _, ok := cache.Get(key); ok {
85 hit++
86 } else {
87 miss++
88 // Add key that was a miss
89 cache.Add(key, key)
90 }
91 }
92
93 b.StopTimer()
94 hitRatio := float64(hit) / float64(b.N)
95 b.ReportMetric(hitRatio, "hit-ratio")
96 }
97
98 // BenchmarkSieveConcurrency benchmarks high concurrency operations
99 func BenchmarkSieveConcurrency(b *testing.B) {
100 cacheSize := 16384
101 cache := sieve.Must(sieve.New[int, int](cacheSize))
102
103 b.ResetTimer()
104
105 // Run a highly concurrent benchmark with many goroutines
106 b.RunParallel(func(pb *testing.PB) {
107 // Each goroutine gets its own random seed
108 r := rand.New(rand.NewSource(rand.Int63()))
109
110 for pb.Next() {
111 // Random operation: get, add, or delete
112 op := r.Intn(10)
113 key := r.Intn(cacheSize * 2) // Half will be misses
114
115 if op < 6 { // 60% gets
116 cache.Get(key)
117 } else if op < 9 { // 30% adds
118 cache.Add(key, key)
119 } else { // 10% deletes
120 cache.Delete(key)
121 }
122 }
123 })
124 }
125
126 // BenchmarkSieveGCPressure specifically measures the impact on garbage collection
127 func BenchmarkSieveGCPressure(b *testing.B) {
128 // Run with different cache sizes
129 for _, cacheSize := range []int{1000, 10000, 50000} {
130 b.Run(fmt.Sprintf("CacheSize_%d", cacheSize), func(b *testing.B) {
131 // Fixed number of operations for consistent measurement
132 operations := 1000000
133
134 // Force GC before test
135 runtime.GC()
136
137 // Capture GC stats before
138 var statsBefore debug.GCStats
139 debug.ReadGCStats(&statsBefore)
140 var memStatsBefore runtime.MemStats
141 runtime.ReadMemStats(&memStatsBefore)
142
143 startTime := time.Now()
144
145 // Create cache with custom allocator
146 cache := sieve.Must(sieve.New[int, int](cacheSize))
147
148 // Run the workload
149 runSieveWorkload(cache, operations)
150
151 elapsedTime := time.Since(startTime)
152
153 // Force GC to get accurate stats
154 runtime.GC()
155
156 // Capture GC stats after
157 var statsAfter debug.GCStats
158 debug.ReadGCStats(&statsAfter)
159 var memStatsAfter runtime.MemStats
160 runtime.ReadMemStats(&memStatsAfter)
161
162 // Report metrics
163 gcCount := statsAfter.NumGC - statsBefore.NumGC
164 pauseTotal := statsAfter.PauseTotal - statsBefore.PauseTotal
165
166 b.ReportMetric(float64(gcCount), "GC-cycles")
167 b.ReportMetric(float64(pauseTotal.Nanoseconds())/float64(operations), "GC-pause-ns/op")
168 b.ReportMetric(float64(memStatsAfter.HeapObjects)/float64(operations), "heap-objs/op")
169 b.ReportMetric(float64(operations)/elapsedTime.Seconds(), "ops/sec")
170
171 // The cache must stay live through the final GC+ReadMemStats
172 // above, or its heap objects vanish from the measurement.
173 runtime.KeepAlive(cache)
174 })
175 }
176 }
177
178 // BenchmarkEviction_LargeCache measures eviction scan time with 1M entries.
179 func BenchmarkEviction_LargeCache(b *testing.B) {
180 const cacheSize = 1_000_000
181 cache := sieve.Must(sieve.New[int, int](cacheSize))
182
183 // Fill the cache completely
184 for i := 0; i < cacheSize; i++ {
185 cache.Add(i, i)
186 }
187 // Mark ~50% as visited so eviction has to scan
188 for i := 0; i < cacheSize; i += 2 {
189 cache.Get(i)
190 }
191
192 b.ResetTimer()
193 for i := 0; i < b.N; i++ {
194 // Each Add beyond capacity triggers an eviction
195 key := cacheSize + i
196 cache.Add(key, key)
197 }
198 }
199
200 // BenchmarkGCPause_Comparison measures GC pause times at various cache sizes.
201 func BenchmarkGCPause_Comparison(b *testing.B) {
202 for _, cacheSize := range []int{100_000, 500_000, 1_000_000} {
203 b.Run(fmt.Sprintf("Size_%d", cacheSize), func(b *testing.B) {
204 cache := sieve.Must(sieve.New[int, int](cacheSize))
205
206 // Fill the cache
207 for i := 0; i < cacheSize; i++ {
208 cache.Add(i, i)
209 }
210
211 // Force GC, snapshot cumulative pause counters so the
212 // reported metric covers only the timed loop (PauseTotalNs
213 // and NumGC are process-cumulative).
214 runtime.GC()
215
216 var before runtime.MemStats
217 runtime.ReadMemStats(&before)
218
219 // Run some operations during the benchmark
220 b.ResetTimer()
221 for i := 0; i < b.N; i++ {
222 key := i % (cacheSize * 2)
223 op := i % 10
224 if op < 6 {
225 cache.Get(key)
226 } else if op < 9 {
227 cache.Add(key, key)
228 } else {
229 cache.Delete(key)
230 }
231 }
232 b.StopTimer()
233
234 // Force GC and measure
235 runtime.GC()
236 var after runtime.MemStats
237 runtime.ReadMemStats(&after)
238 if ngc := after.NumGC - before.NumGC; ngc > 0 {
239 b.ReportMetric(float64(after.PauseTotalNs-before.PauseTotalNs)/float64(ngc), "avg-gc-pause-ns")
240 }
241 b.ReportMetric(float64(after.HeapObjects), "heap-objects")
242 runtime.KeepAlive(cache)
243 })
244 }
245 }
246
247 // BenchmarkMemoryOverhead measures HeapObjects and HeapAlloc at various sizes.
248 func BenchmarkMemoryOverhead(b *testing.B) {
249 for _, cacheSize := range []int{100_000, 500_000, 1_000_000} {
250 b.Run(fmt.Sprintf("Size_%d", cacheSize), func(b *testing.B) {
251 runtime.GC()
252 var before runtime.MemStats
253 runtime.ReadMemStats(&before)
254
255 cache := sieve.Must(sieve.New[int, int](cacheSize))
256 for i := 0; i < cacheSize; i++ {
257 cache.Add(i, i)
258 }
259
260 runtime.GC()
261 var after runtime.MemStats
262 runtime.ReadMemStats(&after)
263
264 b.ReportMetric(float64(after.HeapAlloc-before.HeapAlloc), "heap-bytes-delta")
265 b.ReportMetric(float64(after.HeapObjects-before.HeapObjects), "heap-objects-delta")
266
267 // Run dummy operations so the benchmark doesn't report 0 ns/op
268 b.ResetTimer()
269 for i := 0; i < b.N; i++ {
270 cache.Get(i % cacheSize)
271 }
272
273 // Keep cache alive
274 runtime.KeepAlive(cache)
275 })
276 }
277 }
278
279 // BenchmarkGCPause_Final measures GC pause at 1M entries — the headline number for Phase 4.
280 func BenchmarkGCPause_Final(b *testing.B) {
281 const cacheSize = 1_000_000
282 cache := sieve.Must(sieve.New[int, int](cacheSize))
283
284 // Fill the cache
285 for i := 0; i < cacheSize; i++ {
286 cache.Add(i, i)
287 }
288
289 // Trigger a GC to stabilize, then snapshot the cumulative pause
290 // counters so the reported metric covers only the timed loop.
291 runtime.GC()
292 var before runtime.MemStats
293 runtime.ReadMemStats(&before)
294
295 b.ResetTimer()
296 for i := 0; i < b.N; i++ {
297 key := i % (cacheSize * 2)
298 op := i % 10
299 if op < 6 {
300 cache.Get(key)
301 } else if op < 9 {
302 cache.Add(key, key)
303 } else {
304 cache.Delete(key)
305 }
306 }
307 b.StopTimer()
308
309 runtime.GC()
310 var stats runtime.MemStats
311 runtime.ReadMemStats(&stats)
312 if ngc := stats.NumGC - before.NumGC; ngc > 0 {
313 b.ReportMetric(float64(stats.PauseTotalNs-before.PauseTotalNs)/float64(ngc), "avg-gc-pause-ns")
314 }
315 b.ReportMetric(float64(stats.HeapObjects), "heap-objects")
316 b.ReportMetric(float64(stats.HeapAlloc), "heap-bytes")
317
318 runtime.KeepAlive(cache)
319 }
320
321 // BenchmarkMemoryTotal measures total memory footprint at various cache sizes.
322 func BenchmarkMemoryTotal(b *testing.B) {
323 for _, cacheSize := range []int{100_000, 500_000, 1_000_000} {
324 b.Run(fmt.Sprintf("Size_%d", cacheSize), func(b *testing.B) {
325 runtime.GC()
326 var before runtime.MemStats
327 runtime.ReadMemStats(&before)
328
329 cache := sieve.Must(sieve.New[int, int](cacheSize))
330 for i := 0; i < cacheSize; i++ {
331 cache.Add(i, i)
332 }
333
334 runtime.GC()
335 var after runtime.MemStats
336 runtime.ReadMemStats(&after)
337
338 heapDelta := after.HeapAlloc - before.HeapAlloc
339 b.ReportMetric(float64(heapDelta), "total-heap-bytes")
340 b.ReportMetric(float64(heapDelta)/float64(cacheSize), "bytes-per-entry")
341 b.ReportMetric(float64(after.HeapObjects-before.HeapObjects), "heap-objects-delta")
342
343 // Run dummy ops so benchmark doesn't report 0 ns/op
344 b.ResetTimer()
345 for i := 0; i < b.N; i++ {
346 cache.Get(i % cacheSize)
347 }
348
349 runtime.KeepAlive(cache)
350 })
351 }
352 }
353
354 // BenchmarkEviction_VaryingVisited measures eviction scan cost sensitivity to
355 // the fraction of visited nodes. 100% visited is worst case (full wrap-around).
356 func BenchmarkEviction_VaryingVisited(b *testing.B) {
357 const cacheSize = 100_000
358
359 for _, pctVisited := range []int{0, 50, 90, 100} {
360 b.Run(fmt.Sprintf("Visited_%d%%", pctVisited), func(b *testing.B) {
361 cache := sieve.Must(sieve.New[int, int](cacheSize))
362
363 // Fill the cache
364 for i := 0; i < cacheSize; i++ {
365 cache.Add(i, i)
366 }
367 // Mark pctVisited% as visited
368 visitCount := cacheSize * pctVisited / 100
369 for i := 0; i < visitCount; i++ {
370 cache.Get(i)
371 }
372
373 b.ResetTimer()
374 for i := 0; i < b.N; i++ {
375 key := cacheSize + i
376 cache.Add(key, key)
377 }
378 })
379 }
380 }
381
382 // runWorkload performs a consistent workload that stresses node allocation/deallocation
383 func runSieveWorkload(cache *sieve.Sieve[int, int], operations int) {
384 capacity := cache.Cap()
385
386 // Create a workload that ensures significant cache churn
387 for i := 0; i < operations; i++ {
388 key := i % (capacity * 2) // Ensure we cycle through keys causing evictions
389
390 // Mix of operations: 70% adds, 20% gets, 10% deletes
391 op := i % 10
392 if op < 7 {
393 // Add - heavy on adds to stress allocation
394 cache.Add(key, i)
395 } else if op < 9 {
396 // Get
397 cache.Get(key)
398 } else {
399 // Delete - to trigger freelist recycling
400 cache.Delete(key)
401 }
402
403 // Every so often, add a burst of new entries to trigger evictions
404 if i > 0 && i%10000 == 0 {
405 for j := 0; j < capacity/10; j++ {
406 cache.Add(i+j+capacity, i+j)
407 }
408 }
409 }
410 }