Line data Source code
1 : package cmd
2 :
3 : import (
4 : "context"
5 : "errors"
6 : "fmt"
7 : "io"
8 : "math"
9 : "os"
10 : "sort"
11 :
12 : "github.com/urfave/cli/v3"
13 : "golang.org/x/perf/benchfmt"
14 : )
15 :
16 : // CmdBenchgate は base と PR のベンチ結果を比較し、退化したパッケージを報告するサブコマンド。
17 : var CmdBenchgate = &cli.Command{
18 : Name: "benchgate",
19 : Usage: "compare two benchmark result files and report packages that regressed",
20 : ArgsUsage: "<base.txt> <pr.txt>",
21 : Action: runBenchgate,
22 : }
23 :
24 : // benchRegressThreshold は退化とみなす sec/op geomean 比。2 は2倍。
25 : const benchRegressThreshold = 2.0
26 :
27 : // errBenchgateUsage は比較する2つのファイルが渡されないときに返す
28 : var errBenchgateUsage = errors.New("usage: benchgate <base.txt> <pr.txt>")
29 :
30 : func runBenchgate(_ context.Context, cmd *cli.Command) error {
31 1 : if cmd.Args().Len() != 2 {
32 1 : return errBenchgateUsage
33 1 : }
34 1 : return benchGate(cmd.Writer, cmd.Args().Get(0), cmd.Args().Get(1), benchRegressThreshold)
35 : }
36 :
37 : // benchKey はパッケージとベンチ名の組。
38 : type benchKey struct{ pkg, name string }
39 :
40 : // benchGate は base と pr のベンチファイルを読み、threshold 以上悪化したパッケージを out へ1行ずつ書く。
41 : // 悪化が無ければ何も書かない。
42 : func benchGate(out io.Writer, basePath, prPath string, threshold float64) error {
43 1 : base, err := loadBench(basePath)
44 1 : if err != nil {
45 1 : return fmt.Errorf("read base: %w", err)
46 1 : }
47 1 : pr, err := loadBench(prPath)
48 1 : if err != nil {
49 1 : return fmt.Errorf("read pr: %w", err)
50 1 : }
51 1 : for _, line := range benchRegressions(base, pr, threshold) {
52 1 : if _, err := fmt.Fprintln(out, line); err != nil {
53 1 : return err
54 1 : }
55 : }
56 1 : return nil
57 : }
58 :
59 : // loadBench はベンチファイルを読み、ベンチ名ごとの1操作あたり時間のサンプル列を返す。単位は ns/op でも
60 : // sec/op でもよい。比を取るので単位は打ち消え、base と PR が同じ単位でありさえすればよい。設定行や
61 : // 構文エラー行はベンチ結果でないので読み飛ばす。
62 : func loadBench(path string) (map[benchKey][]float64, error) {
63 1 : f, err := os.Open(path)
64 1 : if err != nil {
65 1 : return nil, err
66 1 : }
67 2 : defer func() { _ = f.Close() }()
68 :
69 1 : out := map[benchKey][]float64{}
70 1 : r := benchfmt.NewReader(f, path)
71 1 : for r.Scan() {
72 1 : res, ok := r.Result().(*benchfmt.Result)
73 1 : if !ok {
74 1 : continue
75 : }
76 1 : v, ok := res.Value("sec/op")
77 1 : if !ok {
78 1 : if v, ok = res.Value("ns/op"); !ok {
79 1 : continue
80 : }
81 : }
82 1 : k := benchKey{res.GetConfig("pkg"), res.Name.String()}
83 1 : out[k] = append(out[k], v)
84 : }
85 1 : return out, r.Err()
86 : }
87 :
88 : // benchRegressions は両方に在るベンチをパッケージごとに突き合わせ、sec/op の median 比の geomean が
89 : // threshold 以上のパッケージを "- <pkg>: geomean x<r>" の行にして名前順で返す。両方に在るベンチだけを
90 : // 見るので、PR だけの新規ベンチや base だけの削除済みベンチには影響されない。
91 : func benchRegressions(base, pr map[benchKey][]float64, threshold float64) []string {
92 1 : type acc struct {
93 1 : sumLog float64
94 1 : n int
95 1 : }
96 1 : byPkg := map[string]*acc{}
97 1 : for k, bvals := range base {
98 1 : pvals, ok := pr[k]
99 1 : if !ok || len(bvals) == 0 || len(pvals) == 0 {
100 1 : continue
101 : }
102 1 : bm, pm := benchMedian(bvals), benchMedian(pvals)
103 1 : if bm <= 0 || pm <= 0 {
104 1 : continue
105 : }
106 1 : a := byPkg[k.pkg]
107 1 : if a == nil {
108 1 : a = &acc{}
109 1 : byPkg[k.pkg] = a
110 1 : }
111 1 : a.sumLog += math.Log(pm / bm)
112 1 : a.n++
113 : }
114 :
115 1 : var lines []string
116 1 : for p, a := range byPkg {
117 1 : geomean := math.Exp(a.sumLog / float64(a.n))
118 1 : if geomean >= threshold {
119 1 : lines = append(lines, fmt.Sprintf("- %s: geomean x%.2f", p, geomean))
120 1 : }
121 : }
122 1 : sort.Strings(lines)
123 1 : return lines
124 : }
125 :
126 : // benchMedian はサンプル列の中央値を返す。呼び出し側のスライスは変更しない。
127 : func benchMedian(xs []float64) float64 {
128 1 : s := append([]float64(nil), xs...)
129 1 : sort.Float64s(s)
130 1 : n := len(s)
131 1 : if n%2 == 1 {
132 1 : return s[n/2]
133 1 : }
134 1 : return (s[n/2-1] + s[n/2]) / 2
135 : }
|