/
profile.go
59 lines (50 loc) · 977 Bytes
/
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
//+build profile
package main
import (
"flag"
"log"
"os"
"runtime/pprof"
"time"
)
var (
profileHeap = flag.String("heapprof", "", "if non-empty, the filename for a pprof heap profile")
profileCPU = flag.String("cpuprof", "", "if non-empty, the filename for a pprof CPU profile")
profileLock = make(chan struct{}, 1)
)
func init() {
profileLock <- struct{}{}
startup = profileStartup
cleanup = profileCleanup
}
func profileStartup() {
if *profileHeap != "" {
f, err := os.Create(*profileHeap)
if err != nil {
log.Fatal(err)
}
go func() {
for {
time.Sleep(time.Second * 5)
l := <-profileLock
f.Seek(0, os.SEEK_SET)
f.Truncate(0)
pprof.Lookup("heap").WriteTo(f, 0)
profileLock <- l
}
}()
}
if *profileCPU != "" {
f, err := os.Create(*profileCPU)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
}
}
func profileCleanup() {
<-profileLock
if *profileCPU != "" {
pprof.StopCPUProfile()
}
}