/
default_histogram.go
63 lines (52 loc) · 1.72 KB
/
default_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
package metrics
import "sync/atomic"
type simpleHistogram struct {
name string
description string
labels string
buckets []uint64
indexes map[uint64]int
values []uint64
sum *uint64
count *uint64
}
func NewHistogram(name string, options ...option) Histogram {
config := configuration{Name: name}
Options.apply(options...)(&config)
indexes := make(map[uint64]int, len(config.Buckets))
for index, bucket := range config.Buckets {
indexes[bucket] = index // bucket
}
var sum, count uint64
this := &simpleHistogram{
name: config.Name,
description: config.Description,
labels: config.RenderLabels(),
buckets: config.Buckets,
indexes: indexes,
values: make([]uint64, len(config.Buckets)),
sum: &sum,
count: &count,
}
config.Exporter.Add(this)
return this
}
func (this *simpleHistogram) Type() string { return "histogram" }
func (this *simpleHistogram) Name() string { return this.name }
func (this *simpleHistogram) Description() string { return this.description }
func (this *simpleHistogram) Labels() string { return this.labels }
func (this *simpleHistogram) Measure(value uint64) {
atomic.AddUint64(this.count, 1)
atomic.AddUint64(this.sum, value)
for index, key := range this.buckets {
if value <= key {
atomic.AddUint64(&this.values[index], 1)
}
}
}
func (this *simpleHistogram) Buckets() []uint64 { return this.buckets }
func (this *simpleHistogram) Value(key uint64) uint64 {
return atomic.LoadUint64(&this.values[this.indexes[key]])
}
func (this *simpleHistogram) Count() uint64 { return atomic.LoadUint64(this.count) }
func (this *simpleHistogram) Sum() uint64 { return atomic.LoadUint64(this.sum) }