-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_bench_test.go
More file actions
94 lines (85 loc) · 2.02 KB
/
cache_bench_test.go
File metadata and controls
94 lines (85 loc) · 2.02 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
package ttlmap_test
import (
"math/rand"
"strconv"
"testing"
"time"
"github.com/packaged/ttlmap"
)
// helper to prepopulate cache with n keys
func prepopulate(c ttlmap.CacheMap, n int) []string {
keys := make([]string, n)
for i := 0; i < n; i++ {
k := "k" + strconv.Itoa(i)
c.Set(k, i, nil)
keys[i] = k
}
return keys
}
func BenchmarkSet(b *testing.B) {
cache := ttlmap.New(ttlmap.WithCleanupDuration(time.Hour)) // disable cleanup overhead
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Set("key"+strconv.Itoa(i), i, nil)
}
}
func BenchmarkGetHit(b *testing.B) {
cache := ttlmap.New(ttlmap.WithCleanupDuration(time.Hour))
keys := prepopulate(cache, 1024)
// rotate through keys
b.ResetTimer()
idx := 0
for i := 0; i < b.N; i++ {
if idx == len(keys) {
idx = 0
}
cache.Get(keys[idx])
idx++
}
}
func BenchmarkGetMiss(b *testing.B) {
cache := ttlmap.New(ttlmap.WithCleanupDuration(time.Hour))
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Get("missing-" + strconv.Itoa(i))
}
}
func BenchmarkParallelSet(b *testing.B) {
cache := ttlmap.New(ttlmap.WithCleanupDuration(time.Hour))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
// local counter to avoid contention on atomics
j := 0
for pb.Next() {
cache.Set("pset-"+strconv.Itoa(j), j, nil)
j++
}
})
}
func BenchmarkParallelGetHit(b *testing.B) {
cache := ttlmap.New(ttlmap.WithCleanupDuration(time.Hour))
keys := prepopulate(cache, 4096)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for pb.Next() {
cache.Get(keys[r.Intn(len(keys))])
}
})
}
func BenchmarkMixedRW(b *testing.B) {
cache := ttlmap.New(ttlmap.WithCleanupDuration(time.Hour))
keys := prepopulate(cache, 2048)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for pb.Next() {
if r.Intn(10) == 0 { // ~10% writes
k := keys[r.Intn(len(keys))]
cache.Set(k, r.Int(), nil)
} else {
cache.Get(keys[r.Intn(len(keys))])
}
}
})
}