-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpercentile_duration.go
62 lines (48 loc) · 1.12 KB
/
percentile_duration.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 stats
import (
"math"
"sort"
"sync"
"time"
)
type PercentileDuration struct {
*sync.Mutex
name string
items []time.Duration
capacity int
}
func NewPercentileDuration(capacity int) *PercentileDuration {
average := &PercentileDuration{
Mutex: &sync.Mutex{},
items: []time.Duration{},
capacity: capacity,
}
return average
}
func (average *PercentileDuration) Push(duration time.Duration) {
average.Lock()
defer average.Unlock()
average.items = append(average.items, duration)
if average.capacity > 0 && len(average.items) > average.capacity {
average.items = average.items[1:]
}
}
func (average *PercentileDuration) Get(count, percents int) time.Duration {
if percents == 0 {
return 0
}
average.Lock()
defer average.Unlock()
if count == 0 {
count = len(average.items)
} else if len(average.items) < count {
count = len(average.items)
}
items := average.items[len(average.items)-count:]
if len(items) == 0 {
return 0
}
sort.Slice(items, func(i, j int) bool { return items[i] < items[j] })
top := int(math.Ceil(float64(len(items)*percents)/100)) - 1
return items[top]
}