-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring_test.go
114 lines (102 loc) · 1.59 KB
/
ring_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
package buffer
import (
"math/rand"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestSimple(t *testing.T) {
r := New(10)
r.Add(1)
r.Add(2)
r.Add(3)
sum := 0
r.Do(func(e interface{}) {
sum += e.(int)
})
assert.Equal(t, 6, sum)
assert.Equal(t, int32(10), r.Capacity())
r.Add(4)
r.Add(5)
r.Add(6)
sum = 0
r.Do(func(e interface{}) {
sum += e.(int)
})
assert.Equal(t, 21, sum)
r.Add(7)
r.Add(8)
r.Add(9)
r.Add(10)
r.Add(11)
r.Add(12)
sum = 0
r.Do(func(e interface{}) {
sum += e.(int)
})
assert.Equal(t, 75, sum)
}
func TestStressRun(t *testing.T) {
add := func(r *Ring, d time.Duration, wg *sync.WaitGroup) {
t.Log("add thread started")
timer := time.NewTimer(d)
for {
select {
case <-timer.C:
wg.Done()
return
default:
r.Add(rand.Int())
}
}
}
sum := func(r *Ring, d time.Duration, wg *sync.WaitGroup) {
t.Log("sum thread started")
timer := time.NewTimer(d)
for {
select {
case <-timer.C:
wg.Done()
return
default:
data := 0
r.Do(func(e interface{}) {
data += e.(int)
})
}
}
}
d := 30 * time.Second
n := 4
r := New(10)
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go add(r, d, &wg)
}
for i := 0; i < n; i++ {
wg.Add(1)
go sum(r, d, &wg)
}
wg.Wait()
}
const size = 64
func BenchmarkAdd(b *testing.B) {
r := New(size)
for i := 0; i < b.N; i++ {
r.Add(i)
}
}
func BenchmarkDo(b *testing.B) {
r := New(size)
for i := 0; i < size; i++ {
r.Add(i)
}
for i := 0; i < b.N; i++ {
data := 0
r.Do(func(e interface{}) {
data += e.(int)
})
}
}