Skip to content

Commit d74b2a9

Browse files
committed
Improve benchmark, "do no harm" optimization.
1 parent e776e0e commit d74b2a9

File tree

2 files changed

+45
-32
lines changed

2 files changed

+45
-32
lines changed

src/cmp/bench_test.go

+34-21
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,56 @@ package cmp_test
22

33
import (
44
"cmp"
5-
"slices"
6-
"strconv"
5+
"math"
76
"testing"
87
)
98

9+
var sum int
10+
1011
func BenchmarkCompare_int(b *testing.B) {
11-
var lst [1_000_000]int
12-
for i := range lst {
13-
lst[i] = i
12+
lst := [...]int{
13+
0xfa3, 0x7fe, 0x03c, 0xcb9,
14+
0x4ce, 0x4fb, 0x7d5, 0x38f,
15+
0x73b, 0x322, 0x85c, 0xf4d,
16+
0xbbc, 0x032, 0x059, 0xb93,
1417
}
15-
b.ResetTimer()
16-
1718
for n := 0; n < b.N; n++ {
18-
slices.SortFunc(lst[:], cmp.Compare)
19+
sum += cmp.Compare(lst[n%len(lst)], lst[(2*n)%len(lst)])
1920
}
2021
}
2122

2223
func BenchmarkCompare_float64(b *testing.B) {
23-
var lst [1_000_000]float64
24-
for i := range lst {
25-
lst[i] = float64(i)
24+
lst := [...]float64{
25+
0.35573281, 0.77552566, 0.19006500, 0.66436280,
26+
0.02769279, 0.97572397, 0.40945068, 0.26422857,
27+
0.10985792, 0.35659522, 0.82752613, 0.18875522,
28+
0.16410543, 0.03578153, 0.51636871, math.NaN(),
2629
}
27-
b.ResetTimer()
28-
2930
for n := 0; n < b.N; n++ {
30-
slices.SortFunc(lst[:], cmp.Compare)
31+
sum += cmp.Compare(lst[n%len(lst)], lst[(2*n)%len(lst)])
3132
}
3233
}
3334

34-
func BenchmarkCompare_string(b *testing.B) {
35-
var lst [1_000_000]string
36-
for i := range lst {
37-
lst[i] = strconv.Itoa(i)
35+
func BenchmarkCompare_strings(b *testing.B) {
36+
lst := [...]string{
37+
"time",
38+
"person",
39+
"year",
40+
"way",
41+
"day",
42+
"thing",
43+
"man",
44+
"world",
45+
"life",
46+
"hand",
47+
"part",
48+
"child",
49+
"eye",
50+
"woman",
51+
"place",
52+
"work",
3853
}
39-
b.ResetTimer()
40-
4154
for n := 0; n < b.N; n++ {
42-
slices.SortFunc(lst[:], cmp.Compare)
55+
sum += cmp.Compare(lst[n%len(lst)], lst[(2*n)%len(lst)])
4356
}
4457
}

src/cmp/cmp.go

+11-11
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,19 @@ func Less[T Ordered](x, y T) bool {
3838
// For floating-point types, a NaN is considered less than any non-NaN,
3939
// a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.
4040
func Compare[T Ordered](x, y T) int {
41-
if x == y {
42-
return 0
43-
}
44-
if x < y {
45-
return -1
46-
}
47-
if isNaN(x) {
48-
if isNaN(y) {
49-
return 0
41+
if x != y {
42+
if isNaN(x) {
43+
if isNaN(y) {
44+
return 0
45+
}
46+
return -1
47+
}
48+
if x < y {
49+
return -1
5050
}
51-
return -1
51+
return +1
5252
}
53-
return +1
53+
return 0
5454
}
5555

5656
// isNaN reports whether x is a NaN without requiring the math package.

0 commit comments

Comments
 (0)