/
profiling.go
70 lines (61 loc) · 1.08 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
package main
import (
"log"
"os"
"runtime"
"runtime/pprof"
)
func startProfiling() func() {
if isProfileEnabled("cpu") {
f, err := os.Create("cpu.pprof")
if err != nil {
log.Fatalln(err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatalln(err)
}
}
if isProfileEnabled("block") {
runtime.SetBlockProfileRate(1)
}
if isProfileEnabled("heap") {
runtime.MemProfileRate = 16 * 1024
}
return dumpProfiles
}
func isProfileEnabled(profile string) bool {
for _, p := range *profiles {
if p == profile {
return true
}
}
return false
}
func dumpProfiles() {
for _, p := range *profiles {
dumpProfile(p)
}
}
func dumpProfile(p string) {
if p == "cpu" {
pprof.StopCPUProfile()
return
}
f, err := os.Create(p + ".pprof")
if err != nil {
log.Fatalln(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatalln("Could not close profile", p, err)
}
}()
prof := pprof.Lookup(p)
if prof != nil {
// print symbolic names in profile to make them human-readable
err = prof.WriteTo(f, 1)
if err != nil {
log.Fatalln(err)
}
}
}