-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile.go
78 lines (62 loc) · 1.37 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
69
70
71
72
73
74
75
76
77
78
package profile
import (
"context"
"fmt"
"os"
"runtime/pprof"
)
type Profile struct {
ctx context.Context
cpuFile *os.File
memFile *os.File
}
func NewProfile(ctx context.Context, cpufileName string, memFileName string) (*Profile, error) {
cpuFile, cerr := os.Create(cpufileName)
if cerr != nil {
return nil, fmt.Errorf("error creating CPU profile: %w", cerr)
}
memFile, merr := os.Create(memFileName)
if merr != nil {
cpuFile.Close()
return nil, fmt.Errorf("error creating memory profile: %w", merr)
}
return &Profile{
ctx: ctx,
cpuFile: cpuFile,
memFile: memFile,
}, nil
}
func (p *Profile) StartCPUProfile() error {
err := pprof.StartCPUProfile(p.cpuFile)
if err != nil {
return fmt.Errorf("error starting CPU profile: %w", err)
}
return nil
}
func (p *Profile) StopCPUProfile() {
pprof.StopCPUProfile()
}
func (p *Profile) WriteHeapProfile() error {
err := pprof.WriteHeapProfile(p.memFile)
if err != nil {
return fmt.Errorf("error writing head memory profile: %w", err)
}
return nil
}
func (p *Profile) Close() error {
var cerr error
var merr error
if p.cpuFile != nil {
cerr = p.cpuFile.Close()
}
if p.memFile != nil {
merr = p.memFile.Close()
}
if cerr != nil {
return fmt.Errorf("error closing CPU profile: %w", cerr)
}
if merr != nil {
return fmt.Errorf("error closing memory profile: %w", merr)
}
return nil
}