forked from tsenart/vegeta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
histogram.go
62 lines (54 loc) · 1.4 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
package vegeta
import (
"fmt"
"strings"
"time"
)
// Buckets represents an Histogram's latency buckets.
type Buckets []time.Duration
// Histogram is a bucketed latency Histogram.
type Histogram struct {
Buckets Buckets
Counts []uint64
Total uint64
}
// Add implements the Add method of the Report interface by finding the right
// Bucket for the given Result latency and increasing its count by one as well
// as the total count.
func (h *Histogram) Add(r *Result) {
if len(h.Counts) != len(h.Buckets) {
h.Counts = make([]uint64, len(h.Buckets))
}
var i int
for ; i < len(h.Buckets)-1; i++ {
if r.Latency >= h.Buckets[i] && r.Latency < h.Buckets[i+1] {
break
}
}
h.Total++
h.Counts[i]++
}
// Nth returns the nth bucket represented as a string.
func (bs Buckets) Nth(i int) (left, right string) {
if i >= len(bs)-1 {
return bs[i].String(), "+Inf"
}
return bs[i].String(), bs[i+1].String()
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (bs *Buckets) UnmarshalText(value []byte) error {
if len(value) < 2 || value[0] != '[' || value[len(value)-1] != ']' {
return fmt.Errorf("bad buckets: %s", value)
}
for _, v := range strings.Split(string(value[1:len(value)-1]), ",") {
d, err := time.ParseDuration(strings.TrimSpace(v))
if err != nil {
return err
}
*bs = append(*bs, d)
}
if len(*bs) == 0 {
return fmt.Errorf("bad buckets: %s", value)
}
return nil
}