-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpuPprof.go
50 lines (45 loc) · 1.15 KB
/
cpuPprof.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
package kbutils
import (
"errors"
"os"
"runtime/pprof"
"sync/atomic"
)
var (
cpuProfiling int32
cpuProfile *os.File
ErrCPUProfileStart = errors.New("CPU profile already start")
ErrCPUProfileNotStart = errors.New("CPU profile not start")
)
func StartCPUProfile(filename string) error {
if atomic.CompareAndSwapInt32(&cpuProfiling, 0, 1) {
cpuProfile, err := os.Create(filename)
if err != nil {
return err
}
return pprof.StartCPUProfile(cpuProfile)
}
return nil
}
func stopCPUProfile() {
if atomic.LoadInt32(&cpuProfiling) == 1 {
pprof.StopCPUProfile()
cpuProfile.Close()
cpuProfile = nil
}
}
// Invoke runtime/pprof.Lookup(name, debug) then save to file.
//
// goroutine - stack traces of all current goroutines
// heap - a sampling of all heap allocations
// threadcreate - stack traces that led to the creation of new OS threads
// block - stack traces that led to blocking on synchronization primitives
//
func saveCPUProfile(name, filename string, debug int) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return pprof.Lookup(name).WriteTo(f, debug)
}