-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice_test.go
128 lines (114 loc) · 2.3 KB
/
slice_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
package sort
import (
"fmt"
"math/rand"
"runtime"
"sort"
"testing"
)
func intsEqual(a, b []int) bool {
if len(a) != len(b) {
return false
}
for idx := range a {
if a[idx] != b[idx] {
return false
}
}
return true
}
func TestSlice(t *testing.T) {
a := make([]int, 1000)
for idx := range a {
a[idx] = rand.Intn(100)
}
cmp0 := make([]int, 1000)
copy(cmp0, a)
Slice(cmp0, func(i, j int) bool {
return cmp0[i] < cmp0[j]
})
cmp1 := make([]int, 1000)
copy(cmp1, a)
sort.Slice(cmp1, func(i, j int) bool {
return cmp1[i] < cmp1[j]
})
if !intsEqual(cmp1, cmp0) {
t.Fatalf("%v != %v", cmp1, cmp0)
}
}
func BenchmarkSliceGenerics(b *testing.B) {
for _, size := range []uint{1, 10, 100, 1000, 10000, 100000} {
b.Run(fmt.Sprintf("%d", size), func(b *testing.B) {
rng := rand.New(rand.NewSource(0))
slices := 1000/size + 30
vs := make([][]int, slices)
for idx := range vs {
vs[idx] = make([]int, size)
s := vs[idx]
for idx := range s {
s[idx] = rng.Intn(int(size)/2 + 1)
}
}
cs := make([][]int, slices)
for idx := range cs {
cs[idx] = make([]int, size)
}
runtime.GC()
runtime.GC()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
idx := uint(i) % slices
if idx == 0 {
b.StopTimer()
for idx := range cs {
copy(cs[idx], vs[idx])
}
b.StartTimer()
}
s := cs[idx]
Slice(s, func(i, j int) bool {
return s[i] < s[j]
})
}
})
}
}
func BenchmarkStdSlice(b *testing.B) {
for _, size := range []uint{1, 10, 100, 1000, 10000, 100000} {
b.Run(fmt.Sprintf("%d", size), func(b *testing.B) {
rng := rand.New(rand.NewSource(0))
slices := 1000/size + 30
vs := make([][]int, slices)
for idx := range vs {
vs[idx] = make([]int, size)
s := vs[idx]
for idx := range s {
s[idx] = rng.Intn(int(size)/2 + 1)
}
}
cs := make([][]int, slices)
for idx := range cs {
cs[idx] = make([]int, size)
}
runtime.GC()
runtime.GC()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
idx := uint(i) % slices
if idx == 0 {
b.StopTimer()
for idx := range cs {
copy(cs[idx], vs[idx])
}
b.StartTimer()
}
s := cs[idx]
sort.Slice(s, func(i, j int) bool {
return s[i] < s[j]
})
}
})
}
}