-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdev_flag.go
55 lines (45 loc) · 1.12 KB
/
dev_flag.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
//go:build dev
package main
import (
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
)
type DevFlag struct {
CPUProf string `kong:"optional,help='CPU profile output file',type='path'"`
CPUProfRate int `kong:"optional,help='CPU profiling rate in Hz',default='100'"`
CPUProfFile *os.File `kong:"-"`
MemProf string `kong:"optional,help='Memory profile output file',type='path'"`
}
func (d DevFlag) StartProfiling() error {
if d.CPUProf != "" {
f, err := os.Create(d.CPUProf)
if err != nil {
return fmt.Errorf("failed to create CPU profile file: %w", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
return fmt.Errorf("failed to start CPU profiling: %w", err)
}
d.CPUProfFile = f
}
return nil
}
func (d DevFlag) StopProfiling() {
if d.CPUProfFile != nil {
pprof.StopCPUProfile()
d.CPUProfFile.Close()
}
if d.MemProf != "" {
f, err := os.Create(d.MemProf)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
defer f.Close()
runtime.GC()
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
}
}