-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint.go
130 lines (115 loc) · 2.26 KB
/
print.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package memdebug
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"runtime"
"runtime/debug"
"runtime/pprof"
"sync"
"time"
)
var lastMemm uint64
var lastMemmm uint64
var printMutex sync.Mutex
const (
mmOff = "[0m"
mmBlue = "[36m"
mmOrange = "[33m"
mmYellow = "[1;33m"
mmGreen = "[32m"
mmMagenta = "[35m"
mmRed = "[1;31m"
)
var isProfiling bool
var gcMode = false
func Profile() {
f, err := os.Create("cpu.pprof")
if err != nil {
log.Fatal("cpu.pprof", err)
}
pprof.StartCPUProfile(f)
isProfiling = true
gcMode = false
}
func GCMode(flag bool) {
gcMode = flag
}
func Print(t time.Time, what ...interface{}) {
printMutex.Lock()
defer printMutex.Unlock()
// OTT memory hacks
ms1 := &runtime.MemStats{}
ms2 := &runtime.MemStats{}
if gcMode {
runtime.ReadMemStats(ms1)
runtime.GC()
debug.FreeOSMemory()
}
runtime.ReadMemStats(ms2)
mmV := ms2.Alloc - lastMemm
cmm := mmYellow
cmmm := mmOff
if ms2.Alloc < lastMemm {
mmV = lastMemm - ms2.Alloc
cmm = mmGreen
}
if ms2.Sys > lastMemmm {
cmmm = mmRed
}
// build up a string and print it once, otherwise the output from different
// threads can easily get gemogrified together
s := fmt.Sprintf("%s%12s%s [%s%4d%s] (%s%8v%s):%10v:%s%10v%s:%10v <- %s %+v%s",
//mmBlue, mtype.method.Name, mmOff,
mmOrange, time.Since(t), mmOff,
mmBlue, runtime.NumGoroutine(), mmOff,
cmm, mmV, mmOff,
ms2.Alloc,
cmmm, ms2.Sys, mmOff,
ms2.StackInuse,
mmMagenta,
what,
mmOff)
fmt.Println(s)
lastMemm = ms2.Alloc
lastMemmm = ms2.Sys
}
var pversion = 1
func DumpProfile() {
pprof.StopCPUProfile()
cmd := exec.Command("go", "tool", "pprof", "-pdf", "./cpu.pprof")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
f, err := os.Create(fmt.Sprintf("cpu-%03d.pdf", pversion))
if err == nil {
io.Copy(f, stdout)
f.Close()
}
cmd.Wait()
pversion++
pprof.StartCPUProfile(f)
}
func WriteProfile() {
pprof.StopCPUProfile()
cmd := exec.Command("go", "tool", "pprof", "-pdf", "./cpu.pprof")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
f, err := os.Create("cpu.pdf")
if err == nil {
io.Copy(f, stdout)
f.Close()
}
cmd.Wait()
}