-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdirectsend_test.go
110 lines (86 loc) · 1.54 KB
/
directsend_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
package benchmarks
import (
"sync"
"sync/atomic"
"testing"
)
func BenchmarkChannelDirectSend(b *testing.B) {
benchmark := func(b *testing.B, buffer int) {
ch := make(chan int, buffer)
wg := sync.WaitGroup{}
var total int
wg.Add(1)
go func() {
defer wg.Done()
for v := range ch {
total += v
}
}()
for i := 0; i < b.N; i++ {
ch <- 1
}
close(ch)
wg.Wait()
}
b.ReportAllocs()
b.Run("direct", func(b *testing.B) {
benchmark(b, 0)
})
b.Run("buffered", func(b *testing.B) {
benchmark(b, 1)
})
b.Run("buffered-10", func(b *testing.B) {
benchmark(b, 10)
})
}
func BenchmarkAtomicAdd(b *testing.B) {
var total int32
b.RunParallel(func(p *testing.PB) {
for p.Next() {
atomic.AddInt32(&total, 1)
}
})
}
func BenchmarkChannelDirectSend2(b *testing.B) {
benchmark := func(b *testing.B, buffer int) {
out := make(chan int, buffer)
back := make(chan int, buffer)
go func() {
for v := range out {
back <- v
}
}()
for i := 0; i < b.N; i++ {
out <- 1
<-back
}
close(out)
close(back)
}
b.ReportAllocs()
b.Run("direct", func(b *testing.B) {
benchmark(b, 0)
})
b.Run("buffered", func(b *testing.B) {
benchmark(b, 1)
})
b.Run("buffered-10", func(b *testing.B) {
benchmark(b, 10)
})
}
func BenchmarkChannelDirectSend3(b *testing.B) {
ch := make(chan int, b.N)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ch <- i
}
close(ch)
k := 0
for j := range ch {
k += j
}
if k != b.N*(b.N-1)/2 {
b.Errorf("K not as expected k=%d, b.N=%d", k, b.N)
}
}