-
Notifications
You must be signed in to change notification settings - Fork 342
/
histogram.go
65 lines (57 loc) · 1.15 KB
/
histogram.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
package stress
import (
"fmt"
"strings"
)
type Histogram struct {
buckets []int64
counters map[int64]int64
min int64
max int64
total int64
}
func NewHistogram(buckets []int64) *Histogram {
return &Histogram{
buckets: buckets,
counters: make(map[int64]int64),
}
}
func (h *Histogram) String() string {
builder := &strings.Builder{}
for _, b := range h.buckets {
builder.WriteString(fmt.Sprintf("%d\t%d\n", b, h.counters[b]))
}
builder.WriteString(fmt.Sprintf("min\t%d\n", h.min))
builder.WriteString(fmt.Sprintf("max\t%d\n", h.max))
builder.WriteString(fmt.Sprintf("total\t%d\n", h.total))
return builder.String()
}
func (h *Histogram) Add(v int64) {
if h.min == 0 || v <= h.min {
h.min = v
}
if v > h.max {
h.max = v
}
h.total++
for _, b := range h.buckets {
if v <= b {
h.counters[b]++
}
}
}
func (h *Histogram) Clone() *Histogram {
buckets := make([]int64, len(h.buckets))
copy(buckets, h.buckets)
counters := make(map[int64]int64)
for k, v := range h.counters {
counters[k] = v
}
return &Histogram{
buckets: buckets,
counters: counters,
min: h.min,
max: h.max,
total: h.total,
}
}