forked from hyperbench/hyperbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebug.go
106 lines (85 loc) · 1.57 KB
/
debug.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"os"
"runtime/pprof"
"time"
)
// Debug related config keys
const (
PprofRecordDuration = "5s"
PprofTimeFmt = "2006-01-02-15-04-05"
)
func debug() {
duration, err := time.ParseDuration(PprofRecordDuration)
if err != nil {
return
}
go recordPProf(duration)
}
func recordPProf(duration time.Duration) {
var (
cpuFilePath string
memFilePath string
cpuFile *os.File
memFile *os.File
)
dir := "./debug"
err := ensurePathExists(dir)
if err != nil {
return
}
// reset inline function
reset := func() {
// use the expected file closed time as the file name's suffix
timeSuffix := time.Now().Add(duration).Format(PprofTimeFmt)
cpuFilePath = fmt.Sprint(dir, "/cpu_", timeSuffix)
memFilePath = fmt.Sprint(dir, "/mem_", timeSuffix)
cpuFile, _ = os.Create(cpuFilePath)
memFile, _ = os.Create(memFilePath)
// start pprof
err := pprof.StartCPUProfile(cpuFile)
if err != nil {
return
}
}
tick := time.NewTicker(duration)
reset()
//nolint
for {
select {
case <-tick.C:
pprof.StopCPUProfile()
err := cpuFile.Close()
if err != nil {
continue
}
err = pprof.WriteHeapProfile(memFile)
if err != nil {
continue
}
err = memFile.Close()
if err != nil {
continue
}
reset()
}
}
}
func ensurePathExists(path string) error {
_, err := os.Stat(path)
// already exist
if err == nil {
return nil
}
// not exist
if os.IsNotExist(err) {
// make full path
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
return nil
}
return err
}