-
Notifications
You must be signed in to change notification settings - Fork 295
/
cpu_metric.go
63 lines (51 loc) · 1.16 KB
/
cpu_metric.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
package metrics
import (
"bytes"
"runtime/pprof"
"time"
"github.com/rs/zerolog/log"
)
type cpuMetric struct {
close func()
writer *bytes.Buffer
idx int
typeMap map[string]float64
}
var cpuMap = map[string]float64{
"ns": float64(time.Nanosecond),
"us": float64(time.Microsecond),
"ms": float64(time.Millisecond),
"s": float64(time.Second),
"hrs": float64(time.Hour),
}
func (c *cpuMetric) getDefault() string {
return "ms"
}
// Start - start gathering metrics for CPU usage
func (c *cpuMetric) start() {
c.idx = 1
c.typeMap = cpuMap
c.writer = bytes.NewBuffer([]byte{})
if err := pprof.StartCPUProfile(c.writer); err != nil {
log.Error().Msgf("failed to write cpu profile")
}
c.close = func() {
pprof.StopCPUProfile()
}
}
// Stop - stop gathering metrics for CPU usage
func (c *cpuMetric) stop() {
c.close()
}
// getWriter returns the profile buffer
func (c *cpuMetric) getWriter() *bytes.Buffer {
return c.writer
}
// getIndex returns the cpu sample index
func (c *cpuMetric) getIndex() int {
return c.idx
}
// getMap returns the map used to format total value
func (c *cpuMetric) getMap() map[string]float64 {
return c.typeMap
}