Source file
src/slices/sort_benchmark_test.go
Documentation: slices
1
2
3
4
5 package slices_test
6
7 import (
8 "cmp"
9 "fmt"
10 "slices"
11 "strings"
12 "testing"
13 )
14
15 func BenchmarkBinarySearchFloats(b *testing.B) {
16 for _, size := range []int{16, 32, 64, 128, 512, 1024} {
17 b.Run(fmt.Sprintf("Size%d", size), func(b *testing.B) {
18 floats := make([]float64, size)
19 for i := range floats {
20 floats[i] = float64(i)
21 }
22 midpoint := len(floats) / 2
23 needle := (floats[midpoint] + floats[midpoint+1]) / 2
24 b.ResetTimer()
25 for i := 0; i < b.N; i++ {
26 slices.BinarySearch(floats, needle)
27 }
28 })
29 }
30 }
31
32 type myStruct struct {
33 a, b, c, d string
34 n int
35 }
36
37 func BenchmarkBinarySearchFuncStruct(b *testing.B) {
38 for _, size := range []int{16, 32, 64, 128, 512, 1024} {
39 b.Run(fmt.Sprintf("Size%d", size), func(b *testing.B) {
40 structs := make([]*myStruct, size)
41 for i := range structs {
42 structs[i] = &myStruct{n: i}
43 }
44 midpoint := len(structs) / 2
45 needle := &myStruct{n: (structs[midpoint].n + structs[midpoint+1].n) / 2}
46 cmpFunc := func(a, b *myStruct) int { return a.n - b.n }
47 b.ResetTimer()
48 for i := 0; i < b.N; i++ {
49 slices.BinarySearchFunc(structs, needle, cmpFunc)
50 }
51 })
52 }
53 }
54
55 func BenchmarkSortFuncStruct(b *testing.B) {
56 for _, size := range []int{16, 32, 64, 128, 512, 1024} {
57 b.Run(fmt.Sprintf("Size%d", size), func(b *testing.B) {
58 structs := make([]*myStruct, size)
59 for i := range structs {
60 structs[i] = &myStruct{
61 a: fmt.Sprintf("string%d", i%10),
62 n: i * 11 % size,
63 }
64 }
65 cmpFunc := func(a, b *myStruct) int {
66 if n := strings.Compare(a.a, b.a); n != 0 {
67 return n
68 }
69 return cmp.Compare(a.n, b.n)
70 }
71
72 slices.SortFunc(structs, cmpFunc)
73 b.ResetTimer()
74 for i := 0; i < b.N; i++ {
75
76 slices.SortFunc(structs, func(a, b *myStruct) int { return cmpFunc(b, a) })
77 slices.SortFunc(structs, cmpFunc)
78 }
79 })
80 }
81 }
82
View as plain text