-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_bench_test.go
More file actions
99 lines (85 loc) · 2.05 KB
/
cache_bench_test.go
File metadata and controls
99 lines (85 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package cache
import (
"context"
"encoding/binary"
"fmt"
"hash/fnv"
"math/rand"
"testing"
"time"
hashmap "github.com/thewizardplusplus/go-hashmap"
)
type IntKey int
func (key IntKey) Hash() int {
hash := fnv.New32()
binary.Write(hash, binary.LittleEndian, int32(key)) // nolint: errcheck
return int(hash.Sum32())
}
func (key IntKey) Equals(other hashmap.Key) bool {
return key == other.(IntKey)
}
func BenchmarkCacheGetting(benchmark *testing.B) {
for _, data := range []struct {
name string
prepare func(cache Cache, storageSize int)
benchmark func(cache Cache, storageSize int)
}{
{
name: "Get",
prepare: func(cache Cache, storageSize int) {
for i := 0; i < storageSize; i++ {
setItem(cache, i)
}
},
benchmark: func(cache Cache, storageSize int) {
cache.Get(IntKey(rand.Intn(storageSize))) // nolint: errcheck
},
},
{
name: "GetWithGC",
prepare: func(cache Cache, storageSize int) {
for i := 0; i < storageSize; i++ {
setItem(cache, i)
}
},
benchmark: func(cache Cache, storageSize int) {
cache.GetWithGC(IntKey(rand.Intn(storageSize))) // nolint: errcheck
},
},
} {
for _, storageSize := range []int{1e2, 1e4, 1e6} {
name := fmt.Sprintf("%s/%d", data.name, storageSize)
benchmark.Run(name, func(benchmark *testing.B) {
cache := NewCache()
data.prepare(cache, storageSize)
// add concurrent load
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(storageSize int) {
ticker := time.NewTicker(time.Nanosecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
setItem(cache, rand.Intn(storageSize))
case <-ctx.Done():
return
}
}
}(storageSize)
benchmark.ResetTimer()
for i := 0; i < benchmark.N; i++ {
data.benchmark(cache, storageSize)
}
})
}
}
}
func setItem(cache Cache, key int) {
var ttl time.Duration
// half of items will be already expired
if rand.Float32() < 0.5 {
ttl = -time.Second
}
cache.Set(IntKey(key), key, ttl)
}