-
Notifications
You must be signed in to change notification settings - Fork 6
/
map_test.go
91 lines (82 loc) · 1.89 KB
/
map_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
package cmap
import (
"fmt"
"sync"
"sync/atomic"
"testing"
)
type TestMap struct {
gomap map[interface{}]interface{}
cmap ConcurrencyMap
gomapnolock map[interface{}]interface{}
sync.RWMutex
}
func NewTestMap() *TestMap {
return &TestMap{gomap: make(map[interface{}]interface{}), cmap: NewConcurrencyMap(), gomapnolock: make(map[interface{}]interface{}, 1024*1024)}
}
func (m *TestMap) GomapNolockGetSet(key interface{}, value interface{}) bool {
m.gomap[key] = value
newvalue := m.gomap[key]
return newvalue == value
}
func (m *TestMap) GomapGetSet(key interface{}, value interface{}) bool {
m.Lock()
m.gomap[key] = value
m.Unlock()
m.RLock()
newvalue := m.gomap[key]
m.RUnlock()
return newvalue == value
}
func (m *TestMap) ConcurrencymapGetSet(key interface{}, value interface{}) bool {
err := m.cmap.Set(key, value)
if err != nil {
return false
}
newvalue, _ := m.cmap.Get(key)
return newvalue == value
}
func BenchmarkGoMap(b *testing.B) {
b.StopTimer()
testmap := NewTestMap()
b.StartTimer()
var i int64 = 0
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
n := atomic.AddInt64(&i, 1)
var key = fmt.Sprintf("foo_%d", n)
result := testmap.GomapGetSet(key, n)
if !result {
b.Error("执行错误错误结果")
}
}
})
}
func BenchmarkNolockGoMap(b *testing.B) {
b.StopTimer()
testmap := NewTestMap()
b.StartTimer()
for i := 0; i < b.N; i++ {
var key = fmt.Sprintf("foo_%d", i)
result := testmap.GomapNolockGetSet(key, i)
if !result {
b.Error("执行错误错误结果")
}
}
}
func BenchmarkConcurrencyMap(b *testing.B) {
b.StopTimer()
testmap := NewTestMap()
b.StartTimer()
var i int64 = 0
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
n := atomic.AddInt64(&i, 1)
var key = fmt.Sprintf("foo_%d", n)
result := testmap.ConcurrencymapGetSet(key, n)
if !result {
b.Error("执行错误错误结果")
}
}
})
}