-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathprofile.go
66 lines (58 loc) · 1.23 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
// +build linux darwin windows
package nimo
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"runtime/trace"
)
func Profiling(port int) {
if port == -1 {
return
}
GoRoutine(func() {
log.Println(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
})
}
func RegisterSignalForPrintStack(sig os.Signal, callback func([]byte)) {
ch := make(chan os.Signal)
signal.Notify(ch, sig)
go func() {
for range ch {
buffer := make([]byte, 1024*1024*4)
runtime.Stack(buffer, true)
callback(buffer)
}
}()
}
func RegisterSignalForProfiling(sig ...os.Signal) {
ch := make(chan os.Signal)
started := false
signal.Notify(ch, sig...)
go func() {
var memoryProfile, cpuProfile, traceProfile *os.File
for range ch {
if started {
pprof.StopCPUProfile()
trace.Stop()
pprof.WriteHeapProfile(memoryProfile)
memoryProfile.Close()
cpuProfile.Close()
traceProfile.Close()
started = false
} else {
// truncate them if already exist
cpuProfile, _ = os.Create("cpu.pprof")
memoryProfile, _ = os.Create("memory.pprof")
traceProfile, _ = os.Create("runtime.trace")
pprof.StartCPUProfile(cpuProfile)
trace.Start(traceProfile)
started = true
}
}
}()
}