forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofilecenter.go
117 lines (99 loc) · 2.19 KB
/
profilecenter.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
package prof
import (
"bytes"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/olekukonko/tablewriter"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/threading"
)
type (
Slot struct {
lifecount int64
lastcount int64
lifecycle int64
lastcycle int64
}
ProfileCenter struct {
lock sync.RWMutex
slots map[string]*Slot
}
)
const flushInterval = 5 * time.Minute
var (
profileCenter = &ProfileCenter{
slots: make(map[string]*Slot),
}
once sync.Once
)
func report(name string, duration time.Duration) {
updated := func() bool {
profileCenter.lock.RLock()
defer profileCenter.lock.RUnlock()
slot, ok := profileCenter.slots[name]
if ok {
atomic.AddInt64(&slot.lifecount, 1)
atomic.AddInt64(&slot.lastcount, 1)
atomic.AddInt64(&slot.lifecycle, int64(duration))
atomic.AddInt64(&slot.lastcycle, int64(duration))
}
return ok
}()
if !updated {
func() {
profileCenter.lock.Lock()
defer profileCenter.lock.Unlock()
profileCenter.slots[name] = &Slot{
lifecount: 1,
lastcount: 1,
lifecycle: int64(duration),
lastcycle: int64(duration),
}
}()
}
once.Do(flushRepeatly)
}
func flushRepeatly() {
threading.GoSafe(func() {
for {
time.Sleep(flushInterval)
logx.Stat(generateReport())
}
})
}
func generateReport() string {
var buffer bytes.Buffer
buffer.WriteString("Profiling report\n")
var data [][]string
calcFn := func(total, count int64) string {
if count == 0 {
return "-"
} else {
return (time.Duration(total) / time.Duration(count)).String()
}
}
func() {
profileCenter.lock.Lock()
defer profileCenter.lock.Unlock()
for key, slot := range profileCenter.slots {
data = append(data, []string{
key,
strconv.FormatInt(slot.lifecount, 10),
calcFn(slot.lifecycle, slot.lifecount),
strconv.FormatInt(slot.lastcount, 10),
calcFn(slot.lastcycle, slot.lastcount),
})
// reset the data for last cycle
slot.lastcount = 0
slot.lastcycle = 0
}
}()
table := tablewriter.NewWriter(&buffer)
table.SetHeader([]string{"QUEUE", "LIFECOUNT", "LIFECYCLE", "LASTCOUNT", "LASTCYCLE"})
table.SetBorder(false)
table.AppendBulk(data)
table.Render()
return buffer.String()
}