-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprofiling.go
More file actions
87 lines (74 loc) · 1.81 KB
/
profiling.go
File metadata and controls
87 lines (74 loc) · 1.81 KB
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
package cli
import (
"fmt"
"os"
"runtime/pprof"
"sync"
)
// File names for profiling output
const (
_cpuprofile = "cpuprofile.pprof"
_memprofile = "memprofile.pprof"
)
// profilingInit starts cpu and memory profiling if enabled.
// It returns a function to stop profiling.
func profilingInit(cpuProfile, memProfile bool) func() {
// doOnStop is a list of functions to be called on stop
var doOnStop []func()
// stop calls all necessary functions to stop profiling
stop := func() {
for _, d := range doOnStop {
if d != nil {
d()
}
}
}
if cpuProfile {
fmt.Println("cpu profile enabled")
// Create profiling file
f, err := os.Create(_cpuprofile)
if err != nil {
fmt.Println("could not create cpu profile file")
return stop
}
// Start profiling
err = pprof.StartCPUProfile(f)
if err != nil {
fmt.Println("could not start cpu profiling")
return stop
}
// Add function to stop cpu profiling to doOnStop list
doOnStop = append(doOnStop, func() {
pprof.StopCPUProfile()
_ = f.Close()
fmt.Println("cpu profile stopped")
})
}
if memProfile {
fmt.Println("memory profile enabled")
// Create profiling file
f, err := os.Create(_memprofile)
if err != nil {
fmt.Println("could not create memory profile file")
return stop
}
// Add function to stop memory profiling to doOnStop list
doOnStop = append(doOnStop, func() {
_ = pprof.WriteHeapProfile(f)
_ = f.Close()
fmt.Println("memory profile stopped")
})
}
return stop
}
// onStopProfiling is called when the cli exits
// profilingOnce makes sure it's only called once
var onStopProfiling func()
var profilingOnce sync.Once
// stopProfiling triggers _stopProfiling.
// It's safe to be called multiple times.
func stopProfiling() {
if onStopProfiling != nil {
profilingOnce.Do(onStopProfiling)
}
}