Debian Codegraph @

internal/cmd/benchcheck/main.go

raw
1 // benchcheck detects performance degradation by comparing the benchmark results
2 // of the current working tree with those of the base branch.
3 //
4 // The working tree is treated as degraded if the mean of all the benchmarks is slower than the base beyond
5 // the tolerance, or if a single benchmark is slower beyond the tolerance of a single benchmark. A single
6 // benchmark of identical code differs by several percent on a shared machine, so its tolerance is large
7 // and the mean, whose noise is far smaller, is what notices a small degradation.
8 //
9 // To make the comparison robust against the load of the machine changing over time,
10 // the base and the working tree are measured alternately for each benchmark function.
11 // While the working tree is degraded, an additional attempt measures both of them again for the benchmarks
12 // which make the mean slow. The noise of a measurement only makes it slower, so the fastest result of all
13 // the attempts is what is compared, for each side.
14 //
15 // The measured results are cached by commit hash:
16 // - the result of the base branch is reused as long as it is measured on the same machine.
17 // - if the working tree is clean, the verdict for the pair of HEAD and the base commit is reused,
18 // so that the command ends immediately.
19 // - if the working tree has uncommitted changes, the working tree is always measured.
20 package main
21
22 import (
23 "context"
24 "errors"
25 "flag"
26 "fmt"
27 "os"
28 "os/exec"
29 "os/signal"
30 "path/filepath"
31 "runtime"
32 "sort"
33 "strings"
34 "syscall"
35 "text/tabwriter"
36 )
37
38 const (
39 defaultAttempts = 3
40 // A measurement consists of multiple short rounds rather than a single long run,
41 // because the fastest round is hardly affected by the temporary load of the machine.
42 // Every layout is measured once by default.
43 defaultRounds = 8
44 // defaultLayouts is the number of the function layouts with which a benchmark is measured.
45 // The fastest layout of each side is compared, so the more layouts are measured,
46 // the less the result depends on how well a single layout happens to fit the code.
47 //
48 // The layouts and the rounds are by -calibrate on the machines of the CI ( 37 decode benchmarks, two
49 // machines for each setting ): identical code linked with other layouts differs by at most 2.4%, 1.8% at
50 // the 90th percentile, with 8 layouts of 300ms; 4 layouts left up to 5.8%, and more rounds of the same
51 // layouts gained nothing, since how the functions are laid out moves a benchmark more than the load does.
52 defaultLayouts = 8
53 defaultBenchTime = "300ms"
54 // defaultTolerance is for the mean of all the benchmarks. The mean of identical code measured
55 // on a shared machine stays within about 1.5%.
56 defaultTolerance = 3.0
57 // defaultSingleTolerance is for a single benchmark, which differs by up to about 8% for identical code
58 // on a shared machine even if the function layout is varied. It exists to notice the degradation of only
59 // a few benchmarks, which hardly moves the mean.
60 defaultSingleTolerance = 15.0
61 )
62
63 var errDegraded = errors.New("performance degradation detected")
64
65 type options struct {
66 baseRef string
67 config benchConfig
68 attempts int
69 // tolerance is for the mean of all the benchmarks, and singleTolerance is for a single benchmark.
70 tolerance float64
71 singleTolerance float64
72 cacheDir string
73 noCache bool
74 // calibrate measures HEAD against itself, to tell how much the measurement of identical code differs.
75 calibrate bool
76 }
77
78 func parseOptions() (*options, error) {
79 var opt options
80 flag.StringVar(&opt.baseRef, "base", "", "git ref to compare with ( default: master, or origin/master if master doesn't exist )")
81 flag.StringVar(&opt.config.Dir, "dir", "benchmarks", "directory of the benchmarks, relative to the repository root")
82 flag.StringVar(&opt.config.Bench, "bench", ".", "pattern of the top-level benchmark functions to run")
83 flag.StringVar(&opt.config.BenchTime, "benchtime", defaultBenchTime, "duration of each round of a benchmark ( go test -benchtime )")
84 flag.IntVar(&opt.config.Rounds, "rounds", defaultRounds, "number of rounds of a measurement: the fastest round is the result of the measurement")
85 flag.IntVar(&opt.config.Layouts, "layouts", defaultLayouts, "number of function layouts of the benchmark binary: the round N is measured with the layout N % layouts ( more than 1 requires Go 1.23 or later )")
86 flag.IntVar(&opt.attempts, "attempts", defaultAttempts, "max number of measurements to reach the result of the base")
87 flag.StringVar(&opt.config.Group, "group", "", "encode or decode: measure only the benchmarks of the group, whose mean is judged apart from the other group ( default: both, in one mean )")
88 shard := flag.String("shard", "", "i/n: measure only the i-th of n parts of the benchmark functions ( 0 <= i < n ), so that n machines measure all of them in parallel. The mean is the one of the part")
89 flag.Float64Var(&opt.tolerance, "tolerance", defaultTolerance, "how much slower ( in percent ) the mean of all the benchmarks may be")
90 flag.Float64Var(&opt.singleTolerance, "single-tolerance", defaultSingleTolerance, "how much slower ( in percent ) a single benchmark may be")
91 flag.StringVar(&opt.cacheDir, "cache-dir", "", "directory to store the results ( default: <git common dir>/benchcheck )")
92 flag.BoolVar(&opt.noCache, "no-cache", false, "ignore the cached results and measure again")
93 flag.BoolVar(&opt.calibrate, "calibrate", false, "measure HEAD against itself, the head linked with other layouts than the base, and print how much the results differ: the noise of the measurement which a comparison has to exceed ( never cached )")
94 flag.Parse()
95 if flag.NArg() != 0 {
96 return nil, fmt.Errorf("unexpected arguments: %s", strings.Join(flag.Args(), " "))
97 }
98 switch opt.config.Group {
99 case "", groupEncode, groupDecode:
100 default:
101 return nil, fmt.Errorf("group must be %s or %s: %q", groupEncode, groupDecode, opt.config.Group)
102 }
103 opt.config.Shards = 1
104 if *shard != "" {
105 if _, err := fmt.Sscanf(*shard, "%d/%d", &opt.config.Shard, &opt.config.Shards); err != nil {
106 return nil, fmt.Errorf("shard must be i/n: %q", *shard)
107 }
108 if opt.config.Shards < 1 || opt.config.Shard < 0 || opt.config.Shard >= opt.config.Shards {
109 return nil, fmt.Errorf("shard must be i/n with 0 <= i < n: %q", *shard)
110 }
111 }
112 if opt.config.Rounds < 1 {
113 return nil, fmt.Errorf("rounds must be greater than zero: %d", opt.config.Rounds)
114 }
115 if opt.config.Layouts < 1 {
116 return nil, fmt.Errorf("layouts must be greater than zero: %d", opt.config.Layouts)
117 }
118 if opt.config.Layouts > opt.config.Rounds {
119 return nil, fmt.Errorf("layouts must not be greater than rounds, otherwise some of them are never measured: layouts %d, rounds %d", opt.config.Layouts, opt.config.Rounds)
120 }
121 if opt.attempts < 1 {
122 return nil, fmt.Errorf("attempts must be greater than zero: %d", opt.attempts)
123 }
124 if opt.tolerance < 0 {
125 return nil, fmt.Errorf("tolerance must not be negative: %v", opt.tolerance)
126 }
127 if opt.singleTolerance < 0 {
128 return nil, fmt.Errorf("single-tolerance must not be negative: %v", opt.singleTolerance)
129 }
130 return &opt, nil
131 }
132
133 func currentMachine(ctx context.Context) (machine, error) {
134 hostname, err := os.Hostname()
135 if err != nil {
136 return machine{}, err
137 }
138 // the version of the go command which builds the benchmarks.
139 out, err := exec.CommandContext(ctx, "go", "env", "GOVERSION").Output()
140 if err != nil {
141 return machine{}, fmt.Errorf("failed to get go version: %w", err)
142 }
143 return machine{
144 Hostname: hostname,
145 GOOS: runtime.GOOS,
146 GOARCH: runtime.GOARCH,
147 NumCPU: runtime.NumCPU(),
148 GoVersion: strings.TrimSpace(string(out)),
149 }, nil
150 }
151
152 func binaryPath(dir, name string) string {
153 if runtime.GOOS == "windows" {
154 name += ".exe"
155 }
156 return filepath.Join(dir, name)
157 }
158
159 type checker struct {
160 opt *options
161 repo *repository
162 cache *cache
163 tmpDir string
164 benchDir string
165
166 baseCommit string
167 base *suite
168 cleanups []func()
169 }
170
171 func (c *checker) cleanup() {
172 for i := len(c.cleanups) - 1; i >= 0; i-- {
173 c.cleanups[i]()
174 }
175 c.cleanups = nil
176 c.base = nil
177 }
178
179 // baseSuite builds the benchmarks for the base commit on the first call.
180 //
181 // The benchmarks of the working tree are built with the library of the base commit,
182 // so that exactly the same benchmarks are compared.
183 // If they can't be built with the base commit ( e.g. they use an API added after it ),
184 // the benchmarks of the base commit itself are used instead.
185 func (c *checker) baseSuite(ctx context.Context) (*suite, error) {
186 if c.base != nil {
187 return c.base, nil
188 }
189 fmt.Printf("build benchmarks for base %s\n", c.baseCommit)
190 baseDir := filepath.Join(c.tmpDir, "base")
191 cleanup, err := c.repo.checkout(ctx, baseDir, c.baseCommit)
192 if err != nil {
193 return nil, err
194 }
195 c.cleanups = append(c.cleanups, cleanup)
196
197 modFile, err := createModFile(ctx, c.tmpDir, c.benchDir, baseDir)
198 if err != nil {
199 return nil, err
200 }
201 base, err := buildSuite(ctx, c.benchDir, modFile, c.tmpDir, "base", c.opt.config.Layouts, 0)
202 if err != nil {
203 fmt.Printf("benchmarks of the working tree can't be built with base %s: use the benchmarks of the base\n", c.baseCommit)
204 base, err = buildSuite(ctx, filepath.Join(baseDir, c.opt.config.Dir), "", c.tmpDir, "base", c.opt.config.Layouts, 0)
205 if err != nil {
206 return nil, err
207 }
208 }
209 c.base = base
210 return base, nil
211 }
212
213 // formatDelta returns how much slower headNs is than baseNs, in percent.
214 func formatDelta(baseNs, headNs float64) string {
215 if baseNs == 0 {
216 // the ratio to zero can't be represented.
217 return "-"
218 }
219 return fmt.Sprintf("%+.2f%%", (headNs-baseNs)/baseNs*100)
220 }
221
222 func printProgress(base, head measurement) {
223 names := make([]string, 0, len(head))
224 for name := range head {
225 names = append(names, name)
226 }
227 sort.Strings(names)
228 for _, name := range names {
229 headNs := head[name]
230 baseNs, exists := base[name]
231 if !exists {
232 fmt.Printf("%s\tbase: -\thead: %.2f ns/op\n", name, headNs)
233 continue
234 }
235 fmt.Printf("%s\tbase: %.2f ns/op\thead: %.2f ns/op\t%s\n", name, baseNs, headNs, formatDelta(baseNs, headNs))
236 }
237 }
238
239 // measureFunc measures the benchmark function fn of the base and of the working tree.
240 // The rounds of both sides are interleaved so that they run under the same load,
241 // and each round uses the next layout so that the fastest layout of each side is compared.
242 // If base is nil, only the working tree is measured.
243 func (c *checker) measureFunc(ctx context.Context, fn string, base, head *suite, baseFirst bool) (measurement, measurement, error) {
244 type side struct {
245 suite *suite
246 result measurement
247 }
248 baseSide := &side{suite: base, result: measurement{}}
249 headSide := &side{suite: head, result: measurement{}}
250 sides := []*side{baseSide, headSide}
251 if !baseFirst {
252 sides = []*side{headSide, baseSide}
253 }
254 for round := 0; round < c.opt.config.Rounds; round++ {
255 for _, s := range sides {
256 if s.suite == nil {
257 continue
258 }
259 result, err := s.suite.run(ctx, round%c.opt.config.Layouts, fn, c.opt.config.BenchTime)
260 if err != nil {
261 return nil, nil, err
262 }
263 s.result.mergeFastest(result)
264 }
265 }
266 return baseSide.result, headSide.result, nil
267 }
268
269 // measure runs the benchmarks until all of them reach the result of the base or the attempts are exhausted.
270 func (c *checker) measure(ctx context.Context, out *outcome) (*measured, error) {
271 m, err := currentMachine(ctx)
272 if err != nil {
273 return nil, err
274 }
275 benchHash, err := hashDir(c.benchDir)
276 if err != nil {
277 return nil, err
278 }
279 key := baselineKey{Config: c.opt.config, Machine: m, BenchHash: benchHash}
280 cached, err := c.cache.loadBaseline(c.baseCommit, key)
281 if err != nil {
282 return nil, err
283 }
284 if cached != nil {
285 fmt.Printf("use cached benchmark results of base %s\n", c.baseCommit)
286 out.cachedBaseline = true
287 }
288
289 fmt.Println("build benchmarks for working tree")
290 // A calibration links the head with other layouts than the base, as a change of the code moves the functions.
291 headSeedOffset := 0
292 if c.opt.calibrate {
293 headSeedOffset = c.opt.config.Layouts
294 }
295 head, err := buildSuite(ctx, c.benchDir, "", c.tmpDir, "head", c.opt.config.Layouts, headSeedOffset)
296 if err != nil {
297 return nil, err
298 }
299 funcs, err := head.funcs(ctx, c.opt.config.Bench)
300 if err != nil {
301 return nil, err
302 }
303 if len(funcs) == 0 {
304 return nil, fmt.Errorf("no benchmark matched %q in %s", c.opt.config.Bench, c.benchDir)
305 }
306 funcs = shardFuncs(groupFuncs(funcs, c.opt.config.Group), c.opt.config.Shard, c.opt.config.Shards)
307 if len(funcs) == 0 {
308 return nil, fmt.Errorf("no benchmark of the group %q in the shard %d/%d", c.opt.config.Group, c.opt.config.Shard, c.opt.config.Shards)
309 }
310
311 cmp := newComparison(c.opt.tolerance, c.opt.singleTolerance)
312 for attempt := 1; attempt <= c.opt.attempts && len(funcs) != 0; attempt++ {
313 fmt.Printf("measure %d benchmark functions ( attempt %d/%d )\n", len(funcs), attempt, c.opt.attempts)
314 // the cached results are valid only for the first attempt:
315 // a retry exists to get rid of the noise, so both sides are measured again at the same time.
316 useCache := attempt == 1 && cached != nil
317 measured := measurement{}
318 for i, fn := range funcs {
319 var baseSuite *suite
320 if !useCache {
321 baseSuite, err = c.baseSuite(ctx)
322 if err != nil {
323 return nil, err
324 }
325 }
326 // alternate the order so that neither side is systematically favored.
327 baseResult, headResult, err := c.measureFunc(ctx, fn, baseSuite, head, i%2 == 0)
328 if err != nil {
329 return nil, err
330 }
331 if useCache {
332 baseResult = cached.Results
333 } else {
334 measured.mergeFastest(baseResult)
335 }
336 cmp.add(fn, baseResult, headResult)
337 printProgress(baseResult, headResult)
338 }
339 if attempt == 1 && cached == nil {
340 if err := c.cache.storeBaseline(&baseline{Commit: c.baseCommit, Key: key, Results: measured}); err != nil {
341 return nil, err
342 }
343 }
344 funcs = cmp.pendingFuncs()
345 }
346 return &measured{results: cmp.sortedResults(), meanDeltaPercent: cmp.meanDeltaPercent()}, nil
347 }
348
349 // measured is the result of the measurement of all the attempts.
350 type measured struct {
351 results []benchResult
352 meanDeltaPercent float64
353 }
354
355 // outcome is the result of a check.
356 type outcome struct {
357 // verdict is nil if there is nothing to compare, because HEAD is the base commit without any change.
358 verdict *verdict
359 cachedVerdict bool
360 cachedBaseline bool
361 }
362
363 func (c *checker) check(ctx context.Context) (*outcome, error) {
364 head, err := c.repo.commit(ctx, "HEAD")
365 if err != nil {
366 return nil, err
367 }
368 // A calibration compares HEAD with itself: it has no base branch to find.
369 base := head
370 if !c.opt.calibrate {
371 base, err = c.repo.baseCommit(ctx, c.opt.baseRef)
372 if err != nil {
373 return nil, err
374 }
375 }
376 dirty, err := c.repo.dirty(ctx)
377 if err != nil {
378 return nil, err
379 }
380 if head == base && !dirty && !c.opt.calibrate {
381 fmt.Printf("HEAD is the base commit %s: nothing to compare\n", base)
382 return &outcome{}, nil
383 }
384
385 key := verdictKey{Config: c.opt.config, Attempts: c.opt.attempts, Tolerance: c.opt.tolerance, SingleTolerance: c.opt.singleTolerance}
386 if !dirty && !c.opt.calibrate {
387 cached, err := c.cache.loadVerdict(head, base, key)
388 if err != nil {
389 return nil, err
390 }
391 if cached != nil {
392 fmt.Printf("use cached verdict of %s against base %s\n", head, base)
393 return &outcome{verdict: cached, cachedVerdict: true}, nil
394 }
395 }
396
397 tmpDir, err := os.MkdirTemp("", "benchcheck-")
398 if err != nil {
399 return nil, err
400 }
401 c.cleanups = append(c.cleanups, func() { os.RemoveAll(tmpDir) })
402 defer c.cleanup()
403 c.tmpDir = tmpDir
404 c.benchDir = filepath.Join(c.repo.root, c.opt.config.Dir)
405 c.baseCommit = base
406
407 out := &outcome{}
408 result, err := c.measure(ctx, out)
409 if err != nil {
410 return nil, err
411 }
412 out.verdict = &verdict{Head: head, Base: base, Key: key, MeanDeltaPercent: result.meanDeltaPercent, Benchmarks: result.results}
413 if !dirty && !c.opt.calibrate {
414 if err := c.cache.storeVerdict(out.verdict); err != nil {
415 return nil, err
416 }
417 }
418 return out, nil
419 }
420
421 func (c *checker) run(ctx context.Context) error {
422 out, err := c.check(ctx)
423 if err != nil {
424 return err
425 }
426 if out.verdict == nil {
427 return nil
428 }
429 if c.opt.calibrate {
430 reportCalibration(out.verdict)
431 return nil
432 }
433 return report(out.verdict)
434 }
435
436 // reportCalibration prints the results of identical code and how much they differ: the mean, the 90th
437 // percentile and the largest of the differences, whichever side is slower.
438 func reportCalibration(v *verdict) {
439 w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
440 fmt.Fprintln(w, "benchmark base ns/op head ns/op delta")
441 var deltas []float64
442 for _, result := range v.Benchmarks {
443 if result.Status != statusOK && result.Status != statusRegressed {
444 continue
445 }
446 fmt.Fprintf(w, "%s %.2f %.2f %s\n", result.Name, result.BaseNs, result.HeadNs, formatDelta(result.BaseNs, result.HeadNs))
447 if result.BaseNs != 0 {
448 d := (result.HeadNs - result.BaseNs) / result.BaseNs * 100
449 if d < 0 {
450 d = -d
451 }
452 deltas = append(deltas, d)
453 }
454 }
455 _ = w.Flush()
456 if len(deltas) == 0 {
457 return
458 }
459 sort.Float64s(deltas)
460 var sum float64
461 for _, d := range deltas {
462 sum += d
463 }
464 fmt.Printf("calibration: %d benchmarks, mean |delta| %.2f%%, p90 %.2f%%, max %.2f%%, mean of the deltas %+.2f%%\n",
465 len(deltas), sum/float64(len(deltas)), deltas[len(deltas)*9/10], deltas[len(deltas)-1], v.MeanDeltaPercent)
466 }
467
468 func report(v *verdict) error {
469 w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
470 fmt.Fprintln(w, "benchmark\tbase ns/op\thead ns/op\tdelta\tattempts\tstatus")
471 regressed := []string{}
472 for _, result := range v.Benchmarks {
473 switch result.Status {
474 case statusOK, statusRegressed:
475 delta := formatDelta(result.BaseNs, result.HeadNs)
476 fmt.Fprintf(w, "%s\t%.2f\t%.2f\t%s\t%d\t%s\n", result.Name, result.BaseNs, result.HeadNs, delta, result.Attempts, result.Status)
477 case statusNew:
478 fmt.Fprintf(w, "%s\t-\t%.2f\t-\t%d\t%s\n", result.Name, result.HeadNs, result.Attempts, result.Status)
479 }
480 if result.Status == statusRegressed {
481 regressed = append(regressed, result.Name)
482 }
483 }
484 if err := w.Flush(); err != nil {
485 return err
486 }
487 fmt.Printf("mean: %+.2f%% ( tolerance %v%% )\n", v.MeanDeltaPercent, v.Key.Tolerance)
488 meanDegraded := v.MeanDeltaPercent > v.Key.Tolerance
489 if !meanDegraded && len(regressed) == 0 {
490 fmt.Printf("OK: not degraded compared with base %s\n", v.Base)
491 return nil
492 }
493 if meanDegraded {
494 fmt.Printf("FAIL: the mean of the benchmarks is slower than base %s beyond the tolerance\n", v.Base)
495 }
496 if len(regressed) != 0 {
497 fmt.Printf("FAIL: %d benchmarks are slower than base %s beyond the tolerance of a single benchmark ( %v%% )\n", len(regressed), v.Base, v.Key.SingleTolerance)
498 for _, name := range regressed {
499 fmt.Printf(" %s\n", name)
500 }
501 }
502 return errDegraded
503 }
504
505 func _main() error {
506 opt, err := parseOptions()
507 if err != nil {
508 return err
509 }
510 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
511 defer stop()
512
513 repo, err := openRepository(ctx)
514 if err != nil {
515 return err
516 }
517 cacheDir := opt.cacheDir
518 if cacheDir == "" {
519 cacheDir, err = repo.defaultCacheDir(ctx)
520 if err != nil {
521 return err
522 }
523 }
524 c := &checker{
525 opt: opt,
526 repo: repo,
527 cache: &cache{dir: cacheDir, readable: !opt.noCache},
528 }
529 return c.run(ctx)
530 }
531
532 func main() {
533 if err := _main(); err != nil {
534 if !errors.Is(err, errDegraded) {
535 fmt.Fprintln(os.Stderr, err)
536 }
537 os.Exit(1)
538 }
539 }
540
541 // shardFuncs returns the functions of the shard-th of shards parts. The functions are dealt to the parts in
542 // the order of their names, one by one: the benchmarks of a kind, whose names are next to each other, are in
543 // every part, so that the parts take about as long as each other.
544 func shardFuncs(funcs []string, shard, shards int) []string {
545 if shards <= 1 {
546 return funcs
547 }
548 sorted := append([]string(nil), funcs...)
549 sort.Strings(sorted)
550 var part []string
551 for i, fn := range sorted {
552 if i%shards == shard {
553 part = append(part, fn)
554 }
555 }
556 return part
557 }
558
559 // groupFuncs returns the functions of the group, or all of them for no group.
560 func groupFuncs(funcs []string, group string) []string {
561 if group == "" {
562 return funcs
563 }
564 var part []string
565 for _, fn := range funcs {
566 if benchmarkGroup(fn) == group {
567 part = append(part, fn)
568 }
569 }
570 return part
571 }