-
Notifications
You must be signed in to change notification settings - Fork 4
/
atomic_test.go
100 lines (90 loc) · 1.64 KB
/
atomic_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
package main
import (
"sync"
"sync/atomic"
"testing"
)
func BenchmarkAtomicInc(b *testing.B) {
var v int32
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
atomic.AddInt32(&v, 1)
}
})
}
func checkZero(v int32) {
if v != 0 {
panic("number should be 0")
}
}
func BenchmarkAtomicRead(b *testing.B) {
var v int32
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
checkZero(atomic.LoadInt32(&v))
}
})
}
func BenchmarkNonAtomicRead(b *testing.B) {
var v int32
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
checkZero(v)
}
})
}
func benchmarkReadWrite(b *testing.B, readPercent int, readFn func() int32, writeFn func(v int32)) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
if i == 100 {
i = 0
}
if i < readPercent {
readFn()
} else {
writeFn(1)
}
}
})
}
func BenchmarkReadWriteAtomicRead90(b *testing.B) {
var v int32
benchmarkReadWrite(b, 90, func() int32 {
return atomic.LoadInt32(&v)
}, func(newV int32) {
atomic.StoreInt32(&v, newV)
})
}
func BenchmarkReadWriteLockRead90(b *testing.B) {
var mu sync.Mutex
var v int32
benchmarkReadWrite(b, 90, func() int32 {
mu.Lock()
v := v
mu.Unlock()
return v
}, func(newV int32) {
mu.Lock()
v = newV
mu.Unlock()
})
}
func BenchmarkAtomicCompareCAS(b *testing.B) {
var atom int32
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
atomic.CompareAndSwapInt32(&atom, 1, 2)
}
})
}
func BenchmarkAtomicCompareReadWrite(b *testing.B) {
var atom int32
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if atomic.LoadInt32(&atom) == 1 {
atomic.CompareAndSwapInt32(&atom, 1, 2)
}
}
})
}