forked from chen3feng/stl4go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap_bench_test.go
117 lines (110 loc) · 2.26 KB
/
heap_bench_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
package stl4go
import (
"container/heap"
"testing"
)
// An intHeap is a min-heap of ints.
type intHeap []int
func (h intHeap) Len() int { return len(h) }
func (h intHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h intHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *intHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *intHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func BenchmarkHeapInit(b *testing.B) {
data := Range(1, 1000)
Shuffle(data)
b.Run("container/heap.Init", func(b *testing.B) {
data = Copy(data)
h := intHeap(data)
b.ResetTimer()
for i := 0; i < b.N; i++ {
heap.Init(&h)
}
})
b.Run("stlgo.MakeMinHeap", func(b *testing.B) {
data = Copy(data)
b.ResetTimer()
for i := 0; i < b.N; i++ {
MakeMinHeap(data)
}
})
b.Run("stlgo.MakeHeapFunc", func(b *testing.B) {
data = Copy(data)
b.ResetTimer()
for i := 0; i < b.N; i++ {
MakeHeapFunc(data, Less[int])
}
})
}
func BenchmarkHeapPush(b *testing.B) {
const count = 1000
b.Run("container/heap.Push", func(b *testing.B) {
h := intHeap([]int{})
for i := 0; i < b.N; i++ {
h = h[0:0]
for n := 0; n < count; n++ {
heap.Push(&h, n)
}
}
})
b.Run("stlgo.PushMinHeap", func(b *testing.B) {
h := []int{}
for i := 0; i < b.N; i++ {
h = h[0:0]
for n := 0; n < count; n++ {
PushMinHeap(&h, n)
}
}
})
b.Run("stlgo.PushHeapFunc", func(b *testing.B) {
h := []int{}
for i := 0; i < b.N; i++ {
h = h[0:0]
for n := 0; n < count; n++ {
PushHeapFunc(&h, n, Less[int])
}
}
})
}
func BenchmarkHeapPop(b *testing.B) {
s := Range(1, 1000)
b.Run("container/heap.Pop", func(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
h := intHeap(Copy(s))
heap.Init(&h)
b.StartTimer()
for len(h) > 0 {
_ = heap.Pop(&h).(int)
}
}
})
b.Run("stlgo.PopMinHeap", func(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
h := Copy(s)
MakeMinHeap(h)
b.StartTimer()
for len(h) > 0 {
_ = PopMinHeap(&h)
}
}
})
b.Run("stlgo.PopHeapFunc", func(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
h := Copy(s)
MakeMinHeap(h)
b.StartTimer()
for len(h) > 0 {
_ = PopHeapFunc(&h, Less[int])
}
}
})
}