/
profile.go
54 lines (48 loc) · 1.15 KB
/
profile.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
package profile
import (
"log"
"os"
"runtime"
"runtime/pprof"
)
func MaybeProfile() func() {
return Profile(os.Getenv("CPUPROFILE"), os.Getenv("MEMPROFILE"))
}
func Profile(cpuProfilePath string, memProfilePath string) func() {
var deferFns []func()
if cpuProfilePath != "" {
f, err := os.Create(cpuProfilePath)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
} else {
deferFns = append(deferFns, func() {
pprof.StopCPUProfile()
if err := f.Close(); err != nil {
log.Fatal("could not close CPU profile: ", err)
}
})
}
}
return func() {
for _, fn := range deferFns {
fn()
}
if memProfilePath != "" {
f, err := os.Create(memProfilePath)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
} else {
runtime.GC() // get up-to-date statistics
if err := f.Close(); err != nil {
log.Fatal("could not close memory profile: ", err)
}
}
}
}
}