-
Notifications
You must be signed in to change notification settings - Fork 147
/
profile.go
68 lines (58 loc) · 1.63 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package profile
import (
"fmt"
"os"
"runtime"
"runtime/pprof"
"github.com/pkg/errors"
)
// Profile manages a CPU and heap profile.
type Profile struct {
// name is the name of the profile.
name string
// cpuProfile is the output file for the CPU profile.
cpuProfile *os.File
}
// New creates a new profile instance. The profiling begins immediately.
func New(name string) (*Profile, error) {
// Open the CPU profile output.
cpuProfile, err := os.Create(fmt.Sprintf("%s_cpu.prof", name))
if err != nil {
return nil, errors.Wrap(err, "unable to create CPU profile")
}
// Start CPU profiling.
if err := pprof.StartCPUProfile(cpuProfile); err != nil {
cpuProfile.Close()
return nil, errors.Wrap(err, "unable to start CPU profile")
}
// Success.
return &Profile{
name: name,
cpuProfile: cpuProfile,
}, nil
}
// Finalize terminates a profile and writes its measurements to disk in the
// current working directory.
func (p *Profile) Finalize() error {
// Close out the CPU profile.
pprof.StopCPUProfile()
if err := p.cpuProfile.Close(); err != nil {
return errors.Wrap(err, "unable to close CPU profile")
}
// Run a GC cycle to update the heap profile statistics.
runtime.GC()
// Write a heap profile.
heapProfile, err := os.Create(fmt.Sprintf("%s_heap.prof", p.name))
if err != nil {
return errors.Wrap(err, "unable to create heap profile")
}
if err := pprof.WriteHeapProfile(heapProfile); err != nil {
heapProfile.Close()
return errors.Wrap(err, "unable to write heap profile")
}
if err := heapProfile.Close(); err != nil {
return errors.Wrap(err, "unable to close heap profile")
}
// Success.
return nil
}