...
1 package profiling
2
3 import (
4 "bytes"
5 "flag"
6 "fmt"
7 _ "net/http/pprof"
8 _ "os"
9 "runtime/pprof"
10 "time"
11 )
12
13 var (
14 cpuprofile = flag.Bool("ge_cpuprofile", false, "enable profiling")
15 profiling = false
16 buf bytes.Buffer
17 profileChannel = make(chan *profileInfo, 10)
18 chan_started = false
19 )
20
21 type profileInfo struct {
22 mtype int
23 started bool
24 }
25
26 func GetBuf() *bytes.Buffer {
27 return &buf
28 }
29
30 func Toggle() {
31 *cpuprofile = !*cpuprofile
32 ProfilingCheckStart()
33 }
34
35 func IsActive() bool {
36 return profiling
37 }
38
39
40 func ProfilingCheckStart() {
41 if !chan_started {
42 go profiler_watcher()
43 chan_started = true
44 }
45 if profiling == *cpuprofile {
46 return
47 }
48 if profiling {
49 ProfilingStop()
50 return
51 }
52 if *cpuprofile {
53
60 fmt.Printf("Starting CPU Profiling...\n")
61 buf.Reset()
62 pprof.StartCPUProfile(&buf)
63 profiling = true
64 profileChannel <- &profileInfo{mtype: 0, started: true}
65 }
66 }
67
68
69 func ProfilingStop() {
70 if profiling {
71 fmt.Printf("Stopping CPU Profiling...\n")
72 profileChannel <- &profileInfo{mtype: 0, started: false}
73 pprof.StopCPUProfile()
74 profiling = false
75 }
76 }
77
78 func profiler_watcher() {
79 for {
80 c := <-profileChannel
81 fmt.Printf("Notification: %v\n", c)
82 for profiling {
83 if buf.Len() > (1024 * 1024 * 10) {
84 fmt.Printf("%v Bufsize: %d\n", profiling, buf.Len())
85 ProfilingStop()
86 }
87 time.Sleep(time.Duration(1) * time.Second)
88 }
89 }
90 }
91
View as plain text