Debian Codegraph @

internal/cmd/benchcheck/bench.go

raw
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "os"
8 "os/exec"
9 "regexp"
10 "runtime"
11 "strconv"
12 "strings"
13 )
14
15 // measurement maps a benchmark name ( without the GOMAXPROCS suffix ) to its ns/op.
16 type measurement map[string]float64
17
18 // mergeFastest merges other into m, keeping the faster result for each benchmark.
19 func (m measurement) mergeFastest(other measurement) {
20 for name, nsPerOp := range other {
21 if prev, exists := m[name]; !exists || nsPerOp < prev {
22 m[name] = nsPerOp
23 }
24 }
25 }
26
27 const (
28 benchmarkPrefix = "Benchmark"
29 nsPerOpUnit = "ns/op"
30 )
31
32 // parseBenchOutput extracts ns/op of every benchmark result line from the output of the benchmarks.
33 //
34 // The output is a text format owned by the testing package, specified at
35 // https://go.dev/design/14313-benchmark-format :
36 //
37 // Benchmark<name>[-<procs>] <iterations> [<value> <unit>...]
38 //
39 // The specification requires readers to ignore every line that is not a benchmark result line,
40 // so such lines are skipped here as well.
41 // If the same benchmark is reported more than once, the fastest result is kept.
42 func parseBenchOutput(output string, procs int) measurement {
43 result := measurement{}
44 for _, line := range strings.Split(output, "\n") {
45 name, nsPerOp, ok := parseBenchLine(line, procs)
46 if !ok {
47 continue
48 }
49 result.mergeFastest(measurement{name: nsPerOp})
50 }
51 return result
52 }
53
54 func parseBenchLine(line string, procs int) (string, float64, bool) {
55 fields := strings.Fields(line)
56 // name and iterations, followed by value/unit pairs.
57 if len(fields) < 2 || len(fields)%2 != 0 {
58 return "", 0, false
59 }
60 if !strings.HasPrefix(fields[0], benchmarkPrefix) {
61 return "", 0, false
62 }
63 if _, err := strconv.ParseUint(fields[1], 10, 64); err != nil {
64 return "", 0, false
65 }
66 for i := 2; i < len(fields); i += 2 {
67 if fields[i+1] != nsPerOpUnit {
68 continue
69 }
70 v, err := strconv.ParseFloat(fields[i], 64)
71 if err != nil {
72 return "", 0, false
73 }
74 return trimProcsSuffix(fields[0], procs), v, true
75 }
76 // the testing package omits ns/op when it is zero:
77 // the elapsed time was below the resolution of the timer, or the benchmark suppressed the metric.
78 return trimProcsSuffix(fields[0], procs), 0, true
79 }
80
81 // trimProcsSuffix removes the "-<GOMAXPROCS>" suffix which the testing package appends
82 // to the benchmark name when GOMAXPROCS is not 1.
83 func trimProcsSuffix(name string, procs int) string {
84 if procs == 1 {
85 return name
86 }
87 return strings.TrimSuffix(name, "-"+strconv.Itoa(procs))
88 }
89
90 // suite is the compiled test binaries of the benchmarks.
91 //
92 // A change of the library shifts where the linker places every function of the binary,
93 // and the alignment of a hot loop alone makes a benchmark faster or slower by more than 10%,
94 // even if the code it runs is not changed at all.
95 // Measuring the same binary again never removes this difference,
96 // so a suite has the binaries of the same code with different function layouts,
97 // and a benchmark is measured with all of them.
98 type suite struct {
99 // binaries is indexed by the layout.
100 binaries []string
101 // dir is the directory of the benchmark package.
102 // The binaries run there, as `go test` does, so that the benchmarks can read their testdata.
103 dir string
104 }
105
106 // buildSuite compiles the benchmarks in dir into the binaries named after name in outDir, one per layout.
107 // If modFile is not empty, it is used instead of go.mod in dir.
108 //
109 // The layout 0 is the default one of the linker, and the others are randomized by the linker
110 // with the layout number as the seed ( -randlayout, supported since Go 1.23 ).
111 // Only the first build compiles the packages: the rest are linked from the build cache.
112 //
113 // The layout N is linked with the seed N + seedOffset of -randlayout ( the seed 0 is the layout of the linker ).
114 func buildSuite(ctx context.Context, dir, modFile, outDir, name string, layouts, seedOffset int) (*suite, error) {
115 s := &suite{dir: dir}
116 for layout := 0; layout < layouts; layout++ {
117 binary := binaryPath(outDir, fmt.Sprintf("%s.layout%d.test", name, layout))
118 args := []string{"test", "-c", "-o", binary}
119 if seed := layout + seedOffset; seed != 0 {
120 args = append(args, "-ldflags", "-randlayout="+strconv.Itoa(seed))
121 }
122 if modFile != "" {
123 args = append(args, "-modfile", modFile)
124 }
125 args = append(args, ".")
126 cmd := exec.CommandContext(ctx, "go", args...)
127 cmd.Dir = dir
128 cmd.Stdout = os.Stderr
129 cmd.Stderr = os.Stderr
130 if err := cmd.Run(); err != nil {
131 return nil, fmt.Errorf("failed to build benchmarks in %s ( layout %d ): %w", dir, layout, err)
132 }
133 s.binaries = append(s.binaries, binary)
134 }
135 return s, nil
136 }
137
138 func (s *suite) exec(ctx context.Context, binary string, args ...string) (string, error) {
139 var stdout bytes.Buffer
140 cmd := exec.CommandContext(ctx, binary, args...)
141 cmd.Dir = s.dir
142 cmd.Stdout = &stdout
143 cmd.Stderr = os.Stderr
144 if err := cmd.Run(); err != nil {
145 // a crashed benchmark reports its reason to stdout.
146 os.Stderr.Write(stdout.Bytes())
147 return "", fmt.Errorf("failed to run %s %s: %w", binary, strings.Join(args, " "), err)
148 }
149 return stdout.String(), nil
150 }
151
152 // comparedLibraries are the libraries which the benchmarks compare go-json with.
153 // Their benchmarks exist to be compared with go-json by hand. They are never measured here,
154 // because the purpose of this command is to notice the degradation of go-json.
155 var comparedLibraries = map[string]struct{}{
156 "EasyJson": {},
157 "EncodingJson": {},
158 "FFJson": {},
159 "FastJson": {},
160 "GoJay": {},
161 "GoJayUnsafe": {},
162 "Jettison": {},
163 "JsonIter": {},
164 "SegmentioJson": {},
165 "Sonic": {},
166 "SonicFast": {},
167 "SonicFastest": {},
168 "SonicStd": {},
169 "StdLib": {},
170 }
171
172 // isComparedLibraryBenchmark reports whether the benchmark function measures a library other than go-json.
173 //
174 // A test binary identifies a benchmark only by its function name, so the library can't be carried
175 // by anything else: the benchmarks are named Benchmark_<operation>_<library>, and the library is
176 // the part after the last underscore. Every other name, including the one without an underscore,
177 // is a benchmark of go-json.
178 func isComparedLibraryBenchmark(name string) bool {
179 i := strings.LastIndexByte(name, '_')
180 if i < 0 {
181 return false
182 }
183 _, exists := comparedLibraries[name[i+1:]]
184 return exists
185 }
186
187 // The groups of the benchmarks, whose means are judged apart: a change of the decoder moves only the decode
188 // benchmarks, which are fewer than the encode ones, so in a mean of both it would count for less than one of
189 // the encoder.
190 const (
191 groupEncode = "encode"
192 groupDecode = "decode"
193 )
194
195 // benchmarkGroup returns the group of the benchmark function.
196 //
197 // A test binary identifies a benchmark only by its function name, so the group can't be carried by anything
198 // else: a benchmark of decoding has Decode or Unmarshal in its name ( BenchmarkCodeDecoder, Benchmark_Decode_*,
199 // BenchmarkUnmarshal* ), and every other one is a benchmark of encoding.
200 func benchmarkGroup(name string) string {
201 if strings.Contains(name, "Decode") || strings.Contains(name, "Unmarshal") {
202 return groupDecode
203 }
204 return groupEncode
205 }
206
207 // funcs returns the names of the top-level benchmark functions of go-json matched by pattern.
208 func (s *suite) funcs(ctx context.Context, pattern string) ([]string, error) {
209 // every layout has the same functions.
210 out, err := s.exec(ctx, s.binaries[0], "-test.list", pattern)
211 if err != nil {
212 return nil, err
213 }
214 names := []string{}
215 for _, name := range strings.Fields(out) {
216 // -test.list also prints tests, fuzz targets and examples.
217 // The testing package distinguishes them only by the prefix of the function name.
218 if !strings.HasPrefix(name, benchmarkPrefix) {
219 continue
220 }
221 if isComparedLibraryBenchmark(name) {
222 continue
223 }
224 names = append(names, name)
225 }
226 return names, nil
227 }
228
229 // run measures a top-level benchmark function, including its sub-benchmarks, with the binary of the layout.
230 // The result is empty if the suite doesn't have the function.
231 func (s *suite) run(ctx context.Context, layout int, fn, benchTime string) (measurement, error) {
232 args := []string{"-test.run", "^$", "-test.bench", "^" + regexp.QuoteMeta(fn) + "$", "-test.count", "1"}
233 if benchTime != "" {
234 args = append(args, "-test.benchtime", benchTime)
235 }
236 out, err := s.exec(ctx, s.binaries[layout], args...)
237 if err != nil {
238 return nil, err
239 }
240 return parseBenchOutput(out, runtime.GOMAXPROCS(0)), nil
241 }