This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmain_test.go
133 lines (110 loc) · 2.42 KB
/
main_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
package main
import (
"sync"
"testing"
)
// Step 1. Use this benchmark to show the CPU Profiler
// Step 2. Use this benchmark to show the Memory Profiler
func BenchmarkInBounds(b *testing.B) {
var mySlice []int
for i := 0; i < 99; i++ {
mySlice = append(mySlice, i)
}
ms := newMySliceType(mySlice)
b.ResetTimer()
for i := 0; i < b.N; i++ {
slicerInBounds(ms)
}
}
// Step 3. Use this benchmark to show the Blocking Profiler
// Step 4. Use this benchmark to show the Mutex Profiler
func BenchmarkInBoundsChannels(b *testing.B) {
var mySlice []int
for i := 0; i < 99; i++ {
mySlice = append(mySlice, i)
}
ms := newMySliceType(mySlice)
b.ResetTimer()
for i := 0; i < b.N; i++ {
slicerInBoundsChannels(ms)
}
}
var pi []int
func printlner(i ...int) {
pi = i
}
type mySliceType struct {
valuesGuard *sync.Mutex
values []int
}
func (s mySliceType) Get(idx int) int {
s.valuesGuard.Lock()
defer s.valuesGuard.Unlock()
checkBuffer(s.values, idx)
return s.values[idx]
}
func (s mySliceType) GetCh(ch chan int, idx int) {
s.valuesGuard.Lock()
defer s.valuesGuard.Unlock()
checkBuffer(s.values, idx)
ch <- s.values[idx]
}
func newMySliceType(values []int) mySliceType {
return mySliceType{
valuesGuard: &sync.Mutex{},
values: values,
}
}
func fillBuffer(slice []int) map[int]int {
result := map[int]int{}
for i := 0; i < 100; i++ {
for j := 0; j < len(slice); j++ {
result[i*len(slice)+j] = slice[j]
}
}
return result
}
func checkBuffer(slice []int, idx int) {
buffer := make(map[int]int, len(slice)*100)
buffer = fillBuffer(slice)
for i := range buffer {
if i == idx {
return
}
}
}
func slicerInBounds(slice mySliceType) {
for i := 0; i < 8; i++ {
a0 := slice.Get(i*8 + 0)
a1 := slice.Get(i*8 + 1)
a2 := slice.Get(i*8 + 2)
a3 := slice.Get(i*8 + 3)
a4 := slice.Get(i*8 + 4)
a5 := slice.Get(i*8 + 5)
a6 := slice.Get(i*8 + 6)
a7 := slice.Get(i*8 + 7)
printlner(a0, a1, a2, a3, a4, a5, a6, a7)
}
}
func slicerInBoundsChannels(slice mySliceType) {
ch := make(chan int, 8)
for i := 0; i < 8; i++ {
go slice.GetCh(ch, i*8+0)
go slice.GetCh(ch, i*8+1)
go slice.GetCh(ch, i*8+2)
go slice.GetCh(ch, i*8+3)
go slice.GetCh(ch, i*8+4)
go slice.GetCh(ch, i*8+5)
go slice.GetCh(ch, i*8+6)
go slice.GetCh(ch, i*8+7)
a0 := <-ch
a1 := <-ch
a2 := <-ch
a3 := <-ch
a4 := <-ch
a5 := <-ch
a6 := <-ch
a7 := <-ch
printlner(a0, a1, a2, a3, a4, a5, a6, a7)
}
}