-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_bench.go
357 lines (320 loc) · 10.2 KB
/
run_bench.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
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
const helpMessage = `
Usage: run_bench [OPTIONS]
Options:
-help Show this help message and exit.
-cooldown=value Set the cooldown period. Valid values:
- "disabled" or "0" to disable cooldown.
- An integer between 1 and 300 (inclusive).
Default: 20 seconds.
-benchtime=value Set the benchmark time duration. Valid value:
- An integer between 1 and 30 (inclusive).
Default: 5 seconds.
-save=value Specify the format to save benchmark results. Valid values:
- "json" to save as JSON format.
- "csv" to save as CSV format.
Default: json.
-wd=value, Set the working directory. Valid value:
-workingdirectory=value - An absolute path to a directory that exists.
Default: project working directory.
Example:
go run run_bench.go -cooldown=10 -benchtime=5 -save=csv -wd=/absolute/path/to/directory
or
go run run_bench.go (it will run with default settings)`
type Run struct {
Name string `json:"name"`
Score float64 `json:"score"`
NsPerOp float64 `json:"nsop"`
}
type BenchmarkResult struct {
Os string `json:"os"`
Arch string `json:"arch"`
Runs []Run `json:"runs"`
RunTime float64 `json:"runTime"`
}
type Parameters struct {
CooldownFunc func()
SaveFunc func([]*BenchmarkResult, string) error
WorkingDirectory string
Benchtime uint
}
func parseBenchmarkOutput(benchmarkOutput string) (*BenchmarkResult, error) {
benchmarkRegex := regexp.MustCompile(`goos:\s+(\w+)\ngoarch:\s+([\w]+)(.*\n)+PASS\nok\s*[a-z \-]+\s*(\d+(\.\d+)?)s`)
matches := benchmarkRegex.FindStringSubmatch(benchmarkOutput)
goos, goarch, runTime := "", "", 0.0
if len(matches) > 0 {
goos = matches[1]
goarch = matches[2]
runTimeSeconds, err := strconv.ParseFloat(matches[4], 64)
if err != nil {
return nil, err
}
runTime = runTimeSeconds
}
benchmarkRunRegex := regexp.MustCompile(`^(Benchmark\w+)-\d+\s+(\d+(\.\d+)?)\s+(\d+(\.\d+)?) ns/op`)
lines := strings.Split(benchmarkOutput, "\n")
runs := make([]Run, 0)
for _, line := range lines {
matches = benchmarkRunRegex.FindStringSubmatch(line)
if len(matches) > 0 {
score, err := strconv.ParseFloat(matches[2], 64)
if err != nil {
return nil, err
}
nsPerOp, err := strconv.ParseFloat(matches[4], 64)
if err != nil {
return nil, err
}
runs = append(runs, Run{
Name: matches[1],
Score: score,
NsPerOp: nsPerOp,
})
}
}
return &BenchmarkResult{
Os: goos,
Arch: goarch,
Runs: runs,
RunTime: runTime,
}, nil
}
func generateCommand(projectDirectory, testFilePath string, benchtimeAmount uint) *exec.Cmd {
benchtime := fmt.Sprintf("-benchtime=%ds", benchtimeAmount)
cmd := exec.Command("go", "test", "-bench=.", benchtime, testFilePath)
cmd.Dir = projectDirectory
return cmd
}
func runCommand(cmd *exec.Cmd) (*BenchmarkResult, error) {
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("#combinedOutput - output: %s, err: %w", string(output), err)
}
return parseBenchmarkOutput(string(output))
}
func findBenchmarkTestFiles(projectDirectory string) ([]string, error) {
var benchmarkFiles []string
if err := filepath.Walk(projectDirectory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(path) == ".go" {
if matched, _ := filepath.Match("*_benchmark_test.go", info.Name()); matched {
relativePath, _ := filepath.Rel(projectDirectory, path)
benchmarkFiles = append(benchmarkFiles, relativePath)
}
}
return nil
}); err != nil {
return nil, err
}
return benchmarkFiles, nil
}
func saveResultsAsJSON(results []*BenchmarkResult, fileName string) error {
fileName = fmt.Sprintf("%s.json", fileName)
file, err := os.Create(fileName)
if err != nil {
return fmt.Errorf("failed to create file %s: %w", fileName, err)
}
defer file.Close()
encoder := json.NewEncoder(file)
if err = encoder.Encode(results); err != nil {
return fmt.Errorf("failed to encode results to JSON: %w", err)
}
return nil
}
func saveResultsAsCSV(results []*BenchmarkResult, fileName string) error {
fileName = fmt.Sprintf("%s.csv", fileName)
file, err := os.Create(fileName)
if err != nil {
return fmt.Errorf("failed to create file %s: %w", fileName, err)
}
defer file.Close()
var sb strings.Builder
sb.WriteString("Name;Score;ns/op\n")
for _, result := range results {
for _, run := range result.Runs {
fmt.Fprintf(&sb, "%s;%.1f;%.1f\n", run.Name, run.Score, run.NsPerOp)
}
}
_, err = file.WriteString(sb.String())
if err != nil {
return fmt.Errorf("failed to write results to CSV: %w", err)
}
return nil
}
func formatTimeAsFileName(t time.Time) string {
return t.Format("2006-01-02_15-04-05")
}
func formatTimeAsStamp(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
func runBenchmarkSuite(parameters Parameters) error {
projectDirectory := parameters.WorkingDirectory
benchmarkTestFiles, err := findBenchmarkTestFiles(projectDirectory)
if err != nil {
return fmt.Errorf("could not find benchmark test files: %w", err)
}
results := make([]*BenchmarkResult, 0)
startTime := time.Now()
fmt.Printf("-- Starting Benchmark Suite at %s\n", formatTimeAsStamp(startTime))
for _, testFile := range benchmarkTestFiles {
fmt.Printf("%s Running benchmark for %s\n", formatTimeAsStamp(time.Now()), testFile)
cmd := generateCommand(projectDirectory, testFile, parameters.Benchtime)
result, err := runCommand(cmd)
if err != nil {
fmt.Printf("Error! Failed to run benchmark for %s. err: %s", testFile, err.Error())
}
results = append(results, result)
parameters.CooldownFunc()
}
endTime := time.Now()
elapsedTime := endTime.Sub(startTime)
fmt.Printf("-- Benchmark Suite completed at %s\n", formatTimeAsStamp(endTime))
fmt.Printf("-- Benchmarks ran for %.2fs\n", elapsedTime.Seconds())
resultFileName := fmt.Sprintf("benchmark_results_%s", formatTimeAsFileName(startTime))
if err = parameters.SaveFunc(results, resultFileName); err != nil {
return fmt.Errorf("could not save benchmark results to file %s: %w", resultFileName, err)
}
return nil
}
func printHelpAndExit() {
fmt.Println(helpMessage)
os.Exit(0)
}
func isHelp(arg string) bool {
arg = strings.ToLower(arg)
return arg == "help" || arg == "-help" || arg == "--help"
}
func cooldownArg(value string) (func(), error) {
switch value {
case "disabled", "0":
return func() {}, nil
}
cooldownAmount, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return nil, fmt.Errorf("illegal value for -cooldown parameter")
}
if cooldownAmount < 1 {
return nil, fmt.Errorf("cooldown could not be a negative number")
}
if cooldownAmount > 300 {
return nil, fmt.Errorf("cooldown could not be greater than 300")
}
return func() {
time.Sleep(time.Duration(cooldownAmount) * time.Second)
}, nil
}
func benchtimeArg(value string) (uint, error) {
benchtime, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return 0, fmt.Errorf("illegal value for -benchtime parameter")
}
if benchtime < 1 {
return 0, fmt.Errorf("benchtime must be a possitive number")
}
if benchtime > 30 {
return 0, fmt.Errorf("benchtime could not be greater than 30")
}
return uint(benchtime), nil
}
func saveArg(value string) (func([]*BenchmarkResult, string) error, error) {
switch value {
case "json":
return saveResultsAsJSON, nil
case "csv":
return saveResultsAsCSV, nil
}
return nil, fmt.Errorf("illegal value for -save parameter")
}
func workingDirectoryArg(path string) (string, error) {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return "", fmt.Errorf("%s does not exists on the system", path)
}
if err != nil {
return "", err
}
if !info.IsDir() {
return "", fmt.Errorf("%s not a directory path", path)
}
if !filepath.IsAbs(path) {
return "", fmt.Errorf("path must be absolute and start with /")
}
return path, nil
}
func ensureResult[T any](result T, err error) T {
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
printHelpAndExit()
}
return result
}
func normalizeString(text string) string {
return strings.ToLower(strings.TrimSpace(text))
}
func parseParameters(args []string) Parameters {
projectDirectory, err := os.Getwd()
if err != nil {
panic(fmt.Errorf("could not read project directory: %w", err))
}
parameters := Parameters{
CooldownFunc: func() { time.Sleep(20 * time.Second) },
Benchtime: 5,
SaveFunc: saveResultsAsJSON,
WorkingDirectory: projectDirectory,
}
for _, arg := range args {
if isHelp(arg) {
printHelpAndExit()
}
// arg format: -key=value
if arg[0] != '-' {
fmt.Printf("Error: All arguments must start with a single hyphen (-)\n")
printHelpAndExit()
}
keyValue := strings.Split(arg[1:], "=")
if len(keyValue) != 2 {
fmt.Printf("Error: Arguments must be in the format -key=value\n")
printHelpAndExit()
}
key, value := normalizeString(keyValue[0]), normalizeString(keyValue[1])
switch key {
case "cooldown":
parameters.CooldownFunc = ensureResult(cooldownArg(value))
case "benchtime":
parameters.Benchtime = ensureResult(benchtimeArg(value))
case "save":
parameters.SaveFunc = ensureResult(saveArg(value))
case "wd", "workingdirectory":
parameters.WorkingDirectory = ensureResult(workingDirectoryArg(value))
default:
fmt.Printf("Error: unknown parameter <%s>. please read the help message 🙏\n", key)
printHelpAndExit()
}
// fmt.Printf("[DEBUG] key: %s, value: %s\n", key, value)
}
return parameters
}
func main() {
// -help
// -cooldown = disable, number[1,300] default 20
// -benchtime = number[1, 30] default 5
// -save = json, csv default json
// -wd, -workingdirectory = string directory default project working directory later
parameters := parseParameters(os.Args[1:])
if err := runBenchmarkSuite(parameters); err != nil {
panic(err)
}
}