-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_benchmark_test.go
145 lines (117 loc) · 2.15 KB
/
cache_benchmark_test.go
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package microcache
import (
"sync"
"testing"
"github.com/golang/groupcache/lru"
"github.com/lpicanco/microcache/configuration"
)
func BenchmarkMapPut(b *testing.B) {
b.StopTimer()
m := make(map[string]interface{})
b.StartTimer()
for i := 0; i < b.N; i++ {
m[string(i)] = i
}
}
func BenchmarkSyncMapPut(b *testing.B) {
b.StopTimer()
var m sync.Map
b.StartTimer()
for i := 0; i < b.N; i++ {
m.Store(string(i), i)
}
}
func BenchmarkGroupCachePut(b *testing.B) {
lru := lru.New(100)
var mu sync.RWMutex
b.ResetTimer()
for i := 0; i < b.N; i++ {
mu.Lock()
lru.Add(i, i)
mu.Unlock()
}
}
func BenchmarkPut(b *testing.B) {
cache := New(configuration.DefaultConfiguration(100))
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Put(string(i), i)
}
}
func BenchmarkMapGet(b *testing.B) {
b.StopTimer()
m := make(map[string]interface{})
for i := 0; i < b.N; i++ {
m[string(i)] = 42
}
b.StartTimer()
for i := 0; i < b.N; i++ {
if m[string(i)] == nil {
b.Fatal()
}
}
}
func BenchmarkSyncMapGet(b *testing.B) {
var m sync.Map
for i := 0; i < b.N; i++ {
m.Store(string(i), 42)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
if _, ok := m.Load(string(i)); !ok {
b.Fatal()
}
}
}
func BenchmarkGet(b *testing.B) {
cache := New(configuration.DefaultConfiguration(100))
for i := 0; i < 100; i++ {
cache.Put(string(i), 42)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
cache.Get(string(i))
}
}
func BenchmarkPutGetConcurrent(b *testing.B) {
cache := New(configuration.DefaultConfiguration(100))
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
cache.Put(string(i), 42)
cache.Get(string(i))
i++
}
})
}
func BenchmarkGroupCacheConcurrent(b *testing.B) {
cache := lru.New(10000)
var mu sync.RWMutex
var wg sync.WaitGroup
wg.Add(b.N * 2)
b.ResetTimer()
for i := 0; i < b.N; i++ {
go func(i int) {
mu.Lock()
cache.Add(i, i)
mu.Unlock()
wg.Done()
}(i)
if i%10 == 3 {
wg.Add(1)
go func(i int) {
mu.Lock()
cache.Remove(i)
mu.Unlock()
wg.Done()
}(i - 1)
}
go func(i int) {
mu.Lock()
cache.Get(i)
mu.Unlock()
wg.Done()
}(i)
}
wg.Wait()
}