/
profiler.go
53 lines (45 loc) · 900 Bytes
/
profiler.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
package main
import (
"os"
"runtime"
"runtime/pprof"
)
type profiler struct {
cpuProfile *os.File
memProfile string
}
// newProfiler creates a profiler that writes to the given files.
// it returns an empty profiler if both files are empty.
// so that stop() will never fail.
func newProfiler(cpuProfile, memProfile string) (profiler, error) {
if cpuProfile == "" {
return profiler{
memProfile: memProfile,
}, nil
}
f, err := os.Create(cpuProfile)
if err != nil {
return profiler{}, err
}
pprof.StartCPUProfile(f)
return profiler{
cpuProfile: f,
memProfile: memProfile,
}, nil
}
func (p *profiler) stop() error {
if p.cpuProfile != nil {
pprof.StopCPUProfile()
p.cpuProfile.Close()
}
if p.memProfile == "" {
return nil
}
f, err := os.Create(p.memProfile)
if err != nil {
return err
}
defer f.Close()
runtime.GC()
return pprof.WriteHeapProfile(f)
}