Debian Codegraph @

sieve_test.go

raw
1 // sieve_test.go - test harness for sieve cache
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 // If you need a commercial license for this work, please contact
9 // the author.
10 //
11 // This software does not come with any express or implied
12 // warranty; it is provided "as is". No claim is made to its
13 // suitability for any purpose.
14
15 package sieve_test
16
17 import (
18 "fmt"
19 "math/rand"
20 "runtime"
21 "strings"
22 "sync"
23 "sync/atomic"
24 "testing"
25 "time"
26
27 "github.com/opencoff/go-sieve"
28 )
29
30 func TestBasic(t *testing.T) {
31 assert := newAsserter(t)
32
33 s := sieve.Must(sieve.New[int, string](4))
34 _, r := s.Add(1, "hello")
35 assert(!r.Hit(), "empty cache: expected clean add of 1")
36
37 _, r = s.Add(2, "foo")
38 assert(!r.Hit(), "empty cache: expected clean add of 2")
39 _, r = s.Add(3, "bar")
40 assert(!r.Hit(), "empty cache: expected clean add of 3")
41 _, r = s.Add(4, "gah")
42 assert(!r.Hit(), "empty cache: expected clean add of 4")
43
44 _, r = s.Add(1, "world")
45 assert(r.Hit(), "key 1: expected to replace")
46
47 _, r = s.Add(5, "boo")
48 assert(!r.Hit(), "adding 5: expected to be new add")
49
50 _, ok := s.Get(2)
51 assert(!ok, "evict: expected 2 to be evicted")
52
53 }
54
55 func TestEvictAll(t *testing.T) {
56 assert := newAsserter(t)
57
58 size := 128
59 s := sieve.Must(sieve.New[int, string](size))
60
61 for i := 0; i < size*2; i++ {
62 val := fmt.Sprintf("val %d", i)
63 _, _, r := s.Probe(i, val)
64 assert(!r.Hit(), "%d: exp new add", i)
65 }
66
67 // the first half should've been all evicted
68 for i := 0; i < size; i++ {
69 _, ok := s.Get(i)
70 assert(!ok, "%d: exp to be evicted", i)
71 }
72
73 // leaving the second half intact
74 for i := size; i < size*2; i++ {
75 ok := s.Delete(i)
76 assert(ok, "%d: exp del on existing cache elem")
77 }
78 }
79
80 func TestAllOps(t *testing.T) {
81 size := 8192
82 vals := randints(size * 3)
83
84 s := sieve.Must(sieve.New[uint64, uint64](size))
85
86 for i := range vals {
87 k := vals[i]
88 s.Add(k, k)
89 }
90
91 vals = shuffle(vals)
92
93 var hit, miss int
94 for i := range vals {
95 k := vals[i]
96 _, ok := s.Get(k)
97 if ok {
98 hit++
99 } else {
100 miss++
101 }
102 }
103
104 t.Logf("%d items: hit %d, miss %d, ratio %4.2f\n", len(vals), hit, miss, float64(hit)/float64(hit+miss))
105 }
106
107 type timing struct {
108 typ string
109 d time.Duration
110 hit, miss uint64
111 }
112
113 type barrier atomic.Uint64
114
115 func (b *barrier) Wait() {
116 v := (*atomic.Uint64)(b)
117 for {
118 if v.Load() == 1 {
119 return
120 }
121 runtime.Gosched()
122 }
123 }
124
125 func (b *barrier) Signal() {
126 v := (*atomic.Uint64)(b)
127 v.Store(1)
128 }
129
130 func TestSpeed(t *testing.T) {
131 size := 32768
132 vals := randints(size * 3)
133 //valr := shuffle(vals)
134
135 // we will start 4 types of workers: add, get, del, probe
136 // each worker will be working on a shuffled version of
137 // the uint64 array.
138
139 for ncpu := 2; ncpu <= 32; ncpu *= 2 {
140 var wg sync.WaitGroup
141
142 wg.Add(ncpu)
143 s := sieve.Must(sieve.New[uint64, uint64](size))
144
145 var bar barrier
146
147 // number of workers of each type
148 m := ncpu / 2
149 ch := make(chan timing, m)
150 for i := 0; i < m; i++ {
151
152 go func(ch chan timing, wg *sync.WaitGroup) {
153 var hit, miss uint64
154
155 bar.Wait()
156 st := time.Now()
157
158 // shuffled array
159 for _, x := range vals {
160 v := x % 16384
161 if _, ok := s.Get(v); ok {
162 hit++
163 } else {
164 miss++
165 }
166 }
167 d := time.Since(st)
168 ch <- timing{
169 typ: "get",
170 d: d,
171 hit: hit,
172 miss: miss,
173 }
174 wg.Done()
175 }(ch, &wg)
176
177 go func(ch chan timing, wg *sync.WaitGroup) {
178 var hit, miss uint64
179 bar.Wait()
180 st := time.Now()
181 for _, x := range vals {
182 v := x % 16384
183 if _, _, r := s.Probe(v, v); r.Hit() {
184 hit++
185 } else {
186 miss++
187 }
188 }
189 d := time.Since(st)
190 ch <- timing{
191 typ: "probe",
192 d: d,
193 hit: hit,
194 miss: miss,
195 }
196 wg.Done()
197 }(ch, &wg)
198 }
199
200 bar.Signal()
201
202 // wait for goroutines to end and close the chan
203 go func() {
204 wg.Wait()
205 close(ch)
206 }()
207
208 // now harvest timing
209 times := map[string]timing{}
210 for tm := range ch {
211 if v, ok := times[tm.typ]; ok {
212 z := (int64(v.d) + int64(tm.d)) / 2
213 v.d = time.Duration(z)
214 v.hit = (v.hit + tm.hit) / 2
215 v.miss = (v.miss + tm.miss) / 2
216 times[tm.typ] = v
217 } else {
218 times[tm.typ] = tm
219 }
220 }
221
222 var out strings.Builder
223 fmt.Fprintf(&out, "Tot CPU %d, workers/type %d %d elems\n", ncpu, m, len(vals))
224 for _, v := range times {
225 var ratio string
226 ns := toNs(int64(v.d), len(vals), m)
227 ratio = hitRatio(v.hit, v.miss)
228 fmt.Fprintf(&out, "%6s %4.2f ns/op%s\n", v.typ, ns, ratio)
229 }
230 t.Logf("%s", out.String())
231 }
232 }
233
234 func shuffle[T ~[]E, E any](v T) []E {
235 i := len(v)
236 for i--; i >= 0; i-- {
237 j := rand.Intn(i + 1)
238 v[i], v[j] = v[j], v[i]
239 }
240 return v
241 }
242
243 func toNs(tot int64, nvals, ncpu int) float64 {
244 return (float64(tot) / float64(nvals)) / float64(ncpu)
245 }
246
247 func hitRatio(hit, miss uint64) string {
248 r := float64(hit) / float64(hit+miss)
249 return fmt.Sprintf(" hit-ratio %4.2f (hit %d, miss %d)", r, hit, miss)
250 }
251
252 func randints(sz int) []uint64 {
253 v := make([]uint64, sz)
254 for i := range v {
255 v[i] = rand.Uint64()
256 }
257 return v
258 }
259
260 func TestProbeFunc(t *testing.T) {
261 assert := newAsserter(t)
262
263 size := 4
264 s := sieve.Must(sieve.New[int, string](size))
265
266 calls := 0
267 mk := func(k int) string {
268 calls++
269 return fmt.Sprintf("val %d", k)
270 }
271
272 // miss: mk called exactly once with the key; result stored
273 v, _, r := s.ProbeFunc(1, mk)
274 assert(!r.Hit(), "probefunc 1: exp miss")
275 assert(calls == 1, "probefunc 1: exp 1 mk call, saw %d", calls)
276 assert(v == "val 1", "probefunc 1: exp 'val 1', saw %q", v)
277
278 g, ok := s.Get(1)
279 assert(ok, "get 1: exp hit after probefunc")
280 assert(g == "val 1", "get 1: exp 'val 1', saw %q", g)
281
282 // hit: mk not called; cached value returned, not a freshly made one
283 v, _, r = s.ProbeFunc(1, func(k int) string { calls++; return "other" })
284 assert(r.Hit(), "probefunc 1 again: exp hit")
285 assert(calls == 1, "probefunc 1 again: mk must not be called, saw %d calls", calls)
286 assert(v == "val 1", "probefunc 1 again: exp cached 'val 1', saw %q", v)
287
288 // fill to capacity, then one more miss must report an eviction
289 for i := 2; i <= size; i++ {
290 _, _, r = s.ProbeFunc(i, mk)
291 assert(!r.Hit(), "probefunc %d: exp miss", i)
292 assert(!r.Evicted(), "probefunc %d: exp no eviction", i)
293 }
294 v, ev, r := s.ProbeFunc(size+1, mk)
295 assert(!r.Hit(), "probefunc %d: exp miss", size+1)
296 assert(r.Evicted(), "probefunc %d: exp eviction", size+1)
297 assert(v == fmt.Sprintf("val %d", size+1), "probefunc %d: exp new val, saw %q", size+1, v)
298 assert(ev.Val == fmt.Sprintf("val %d", ev.Key), "evicted <%d, %q>: mismatched", ev.Key, ev.Val)
299 assert(calls == size+1, "exp %d mk calls, saw %d", size+1, calls)
300 }