-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
370 lines (295 loc) · 8.04 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
arg "github.com/alexflint/go-arg"
)
var (
// These will be set by Goreleaser.
version = "v0.5"
commit = ""
date = ""
)
var goExe = "go"
func init() {
if exe := os.Getenv("GOEXE"); exe != "" {
goExe = exe
}
}
type config struct {
Bench string `help:"run only those benchmarks matching a regular expression"`
Count int `help:"run benchmark count times"`
Package string `arg:"" help:"package to test (e.g. ./lib)" default:"."`
Base string `help:"Git version (tag, branch etc.) to compare with. Leave empty to run on current branch only."`
BaseGoExe string `help:"The Go binary to use for the second run."`
NoStash bool `help:"Don't stash uncommited changes (just run the benchmark against the current code)."`
Tags string `help:"Build -tags"`
Race bool `help:"Run with -race flag"`
IncludeRuntime bool `help:"Include runtime in the profile."`
Cpu string `help:"a comma separated list of CPU counts, e.g. -cpu 1,2,3,4"`
ProfType string `help:"write a profile of the given type and run pprof; valid types are 'cpu', 'mem', 'block'."`
ProfCallgrind bool `help:"write a cpu profile and callgrind data and run qcachegrind"`
ProfSampleIndex string `help:"pprof sample index"`
OutDir string `help:"directory to write files to. Defaults to a temp dir."`
}
// Number of runs when comparing branches (if not set).
const benchStatCountCompare = 4
func main() {
var cfg config
// Defaults
cfg.Bench = "Bench*"
p := arg.MustParse(&cfg)
if cfg.ProfType != "" {
if cfg.ProfType != "mem" && cfg.ProfType != "cpu" && cfg.ProfType != "block" {
p.Fail(fmt.Sprintf("invalid profile type %q. Must be one of %v", cfg.ProfType, []string{"mem", "cpu", "block"}))
}
}
if cfg.OutDir == "" {
var err error
cfg.OutDir, err = os.MkdirTemp("", "gobench")
checkErr("create temp dir", err)
defer os.Remove(cfg.OutDir)
}
r := runner{currentBranch: getCurrentBranch(), config: cfg}
if r.Base != "" {
fmt.Printf("Benchmark and compare branch %q and %q.\n", r.Base, r.currentBranch)
} else {
fmt.Printf("Benchmark branch %q\n", r.currentBranch)
}
r.runBenchmarks()
if r.profilingEnabled() {
r.runPprof()
}
}
type runner struct {
currentBranch string
config
}
func (r *runner) runBenchmarks() {
var hasUncommitted bool
if !r.NoStash {
hasUncommitted = hasUncommittedChanges()
if hasUncommitted && r.Base != "" {
log.Fatal("error: --base set, but there are uncommited changes.")
}
if r.Base == "" && hasUncommitted {
// Compare to a stashed version.
r.Base = "stash"
}
}
if r.Count == 0 {
r.Count = 1
if r.Base != "" || r.BaseGoExe != "" {
r.Count = benchStatCountCompare
}
}
first, second := r.Base, r.currentBranch
exe1, exe2 := goExe, r.BaseGoExe
if exe2 == "" {
exe2 = exe1
}
if hasUncommitted {
// Stash and compare
fmt.Println("Stash changes")
stash("save")
checkErr("run benchmark", r.runBenchmark(exe1, first))
stash("pop")
} else if r.Base != "" || r.BaseGoExe != "" {
if first == "" {
first = r.currentBranch
}
// Start with the "left" branch
checkErr("checkout base", r.checkout(first))
checkErr("run benchmark", r.runBenchmark(exe1, first))
if second != first {
checkErr("checkout current branch", r.checkout(second))
}
}
checkErr("run benchmark", r.runBenchmark(exe2, second))
// Make it stand out a little.
fmt.Print("\n\n")
checkErr("run benchstat", r.runBenchStat(first, second))
}
func (r runner) runBenchmark(exeName, name string) error {
args := append(r.asBenchArgs(name), r.Package)
b, _ := exec.Command(exeName, "version").CombinedOutput()
fmt.Println("\n", string(b))
cmd := exec.Command(exeName, args...)
f, err := r.createBenchOutputFile(name)
if err != nil {
return err
}
defer f.Close()
output := io.MultiWriter(f, os.Stdout)
cmd.Stdout = output
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return fmt.Errorf("failed to execute %q: %s", exeName, err)
}
return nil
}
func (r runner) runBenchStat(name1, name2 string) error {
if name2 == "" {
return errors.New("no second name")
}
var filename1, filename2 string
if name1 != "" {
filename1 = r.benchOutFilename(name1)
}
filename2 = r.benchOutFilename(name2)
const cmdName = "benchstat"
args := []string{"-sort", "name"}
if name1 != "" {
args = []string{filename1, filename2}
} else {
args = []string{filename2}
}
output, err := exec.Command(cmdName, args...).CombinedOutput()
if err != nil {
return err
}
fmt.Println(string(output))
return nil
}
func (r runner) runPprof() error {
args := []string{"tool", "pprof"}
if r.Base != "" {
args = append(args, "-diff_base", r.profileOutFilename(r.Base))
}
if !r.IncludeRuntime {
args = append(args, "--ignore=runtime")
}
if r.ProfType == "mem" && r.ProfSampleIndex == "" {
args = append(args, "--alloc_objects")
}
if r.ProfSampleIndex != "" {
args = append(args, "-sample_index="+r.ProfSampleIndex)
}
// go tool pprof -callgrind -output callgrind.out innercpu.pprof
if r.ProfCallgrind {
cf := r.callgrindOutFilename()
args = append(args, "-callgrind", "-output", cf)
}
args = append(args, r.profileOutFilename(r.currentBranch))
cmd := exec.Command(goExe, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
if r.ProfCallgrind {
cmd := exec.Command("qcachegrind", r.callgrindOutFilename())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Start(); err != nil {
return err
}
return cmd.Wait()
}
return nil
}
func (r runner) checkout(branch string) error {
output, err := exec.Command("git", "checkout", branch).CombinedOutput()
if err != nil {
return err
}
fmt.Println(string(output))
return nil
}
func getCurrentBranch() string {
output, err := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD").Output()
checkErr("get current branch", err)
return strings.TrimSpace(string(output))
}
func stash(command string) string {
output, err := exec.Command("git", "stash", command).Output()
checkErr("stash", err)
return strings.TrimSpace(string(output))
}
func hasUncommittedChanges() bool {
_, err := exec.Command("git", "diff-index", "--quiet", "HEAD", "--").Output()
if err == nil {
return false
}
if _, ok := err.(*exec.ExitError); ok {
return true
}
log.Fatal(err)
return true
}
func checkErr(what string, err error) {
if err != nil {
log.Fatal(what+": ", "Error: ", err)
}
}
func (c config) asBenchArgs(name string) []string {
args := []string{
"test",
"-run", "NONE",
"-bench", c.Bench,
fmt.Sprintf("-count=%d", c.Count),
"-test.benchmem=true",
"-timeout", "40m",
}
if c.Race {
args = append(args, "-race")
}
if c.Tags != "" {
args = append(args, "-tags", c.Tags)
}
if c.ProfType != "" {
args = append(args, fmt.Sprintf("-%sprofile", c.ProfType), c.profileOutFilename(name))
}
if c.Cpu != "" {
args = append(args, "-cpu", c.Cpu)
}
return args
}
func (c config) normalizeName(name string) string {
// Slashes in branch names.
return strings.ReplaceAll(name, "/", "-")
}
func (c config) benchOutFilename(name string) string {
return filepath.Join(c.OutDir, c.normalizeName(name)+".bench")
}
func (c config) profileOutFilename(name string) string {
return filepath.Join(c.OutDir, (c.normalizeName(name) + ".pprof"))
}
func (c config) callgrindOutFilename() string {
return filepath.Join(c.OutDir, ("callgrind.out"))
}
func (c config) profilingEnabled() bool {
return c.ProfType != ""
}
func (c config) createBenchOutputFile(name string) (io.WriteCloser, error) {
f, err := os.Create(c.benchOutFilename(name))
if err != nil {
return nil, err
}
return f, nil
}
func (c config) Version() string {
version := "gobench " + version
if commit != "" || date != "" {
version += ","
}
if commit != "" {
version += " " + commit
}
if date != "" {
version += " " + date
}
return version
}