-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathprofiling.go
76 lines (64 loc) · 1.33 KB
/
profiling.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
//go:build !rare_no_pprof
package main
import (
"fmt"
"os"
"runtime/pprof"
"time"
"github.com/urfave/cli/v2"
)
var profilerDone chan bool
func startProfiler(basename string) {
fcpu, _ := os.Create(basename + ".cpu.prof")
pprof.StartCPUProfile(fcpu)
profilerDone = make(chan bool)
go func() {
idx := 0
OUTER_LOOP:
for {
select {
case <-time.After(500 * time.Millisecond):
filename := fmt.Sprintf("%s_%03d.prof", basename, idx)
if f, err := os.Create(filename); err == nil {
pprof.WriteHeapProfile(f)
}
idx++
case <-profilerDone:
break OUTER_LOOP
}
}
}()
}
func stopProfile() {
pprof.StopCPUProfile()
profilerDone <- true
}
func init() {
appModifiers = append(appModifiers, func(app *cli.App) {
app.Flags = append(app.Flags, &cli.StringFlag{
Name: "profile",
Usage: "Write application profiling information as part of execution. Specify base-name",
})
oldBefore := app.Before
app.Before = func(c *cli.Context) error {
if c.IsSet("profile") {
basename := c.String("profile")
startProfiler(basename)
}
if oldBefore != nil {
return oldBefore(c)
}
return nil
}
oldAfter := app.After
app.After = func(c *cli.Context) error {
if c.IsSet("profile") {
stopProfile()
}
if oldAfter != nil {
return oldAfter(c)
}
return nil
}
})
}