Debian Codegraph @

bench_test.go

raw symbols SCIP
1 package golang_fifo
2
3 import (
4 "strconv"
5 "testing"
6
7 "github.com/scalalang2/golang-fifo/sieve"
8 )
9
10 type value struct {
11 bytes []byte
12 }
13
14 type compositeKey struct {
15 key1 string
16 key2 string
17 }
18
19 type benchTypes interface {
20 int32 | int64 | string | compositeKey
21 }
22
23 func BenchmarkCache(b *testing.B) {
24 b.Run("cache=sieve", func(b *testing.B) {
25 b.Run("t=int32", bench[int32](genKeysInt32))
26 b.Run("t=int64", bench[int64](genKeysInt64))
27 b.Run("t=string", bench[string](genKeysString))
28 b.Run("t=composite", bench[compositeKey](genKeysComposite))
29 })
30 }
31
32 func bench[T benchTypes](gen func(workload int) []T) func(b *testing.B) {
33 cacheSize := 100000
34
35 return func(b *testing.B) {
36 benchmarkSieveCache[T](b, cacheSize, gen)
37 }
38 }
39
40 func genKeysInt32(workload int) []int32 {
41 keys := make([]int32, workload)
42 for i := range keys {
43 keys[i] = int32(i)
44 }
45 return keys
46 }
47
48 func genKeysInt64(workload int) []int64 {
49 keys := make([]int64, workload)
50 for i := range keys {
51 keys[i] = int64(i)
52 }
53 return keys
54 }
55
56 func genKeysString(workload int) []string {
57 keys := make([]string, workload)
58 for i := range keys {
59 keys[i] = strconv.Itoa(i)
60 }
61 return keys
62 }
63
64 func genKeysComposite(workload int) []compositeKey {
65 keys := make([]compositeKey, workload)
66 for i := range keys {
67 keys[i].key1 = strconv.Itoa(i)
68 keys[i].key2 = strconv.Itoa(i)
69 }
70 return keys
71 }
72
73 func benchmarkSieveCache[T benchTypes](b *testing.B, cacheSize int, genKey func(size int) []T) {
74 cache := sieve.New[T, value](cacheSize, 0)
75 keys := genKey(b.N)
76 b.ResetTimer()
77 for i := 0; i < b.N; i++ {
78 key := keys[i]
79 cache.Set(key, value{
80 bytes: make([]byte, 10),
81 })
82 cache.Get(key)
83 }
84 cache.Purge()
85 }