-
Notifications
You must be signed in to change notification settings - Fork 2
/
prof.go
63 lines (56 loc) · 1.53 KB
/
prof.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
package vinamax2
// provides run-time profiling.
import (
"io/ioutil"
"os"
"os/exec"
"runtime/pprof"
)
// start CPU profiling, safe to cpu.pprof
func InitCPUProfile() {
fname := "cpu.pprof"
f, err := os.Create(fname)
FatalErr(err)
err = pprof.StartCPUProfile(f)
FatalErr(err)
Log("writing CPU profile to", fname)
// at exit: exec go tool pprof to generate SVG output
AtExit(func() {
pprof.StopCPUProfile()
me := procSelfExe()
outfile := fname + ".svg"
saveCmdOutput(outfile, "go", "tool", "pprof", "-svg", me, fname)
})
}
// start memory profiling
func InitMemProfile() {
Log("memory profile enabled")
AtExit(func() {
fname := "mem.pprof"
f, err := os.Create(fname)
defer f.Close()
LogErr(err, "memory profile") // during cleanup, should not panic/exit
Log("writing memory profile to", fname)
LogErr(pprof.WriteHeapProfile(f), "memory profile")
me := procSelfExe()
outfile := fname + ".svg"
saveCmdOutput(outfile, "go", "tool", "pprof", "-svg", "--inuse_objects", me, fname)
})
}
// Exec command and write output to outfile.
func saveCmdOutput(outfile string, cmd string, args ...string) {
Log("exec:", cmd, args, ">", outfile)
out, err := exec.Command(cmd, args...).Output() // TODO: stderr is ignored
if err != nil {
Log("exec ", cmd, args, err, string(out))
}
// on error: write anyway, clobbers output file.
e := ioutil.WriteFile(outfile, out, 0666)
LogErr(e, "writing", outfile)
}
// path to the executable.
func procSelfExe() string {
me, err := os.Readlink("/proc/self/exe")
PanicErr(err)
return me
}