-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecorrelated.go
More file actions
49 lines (43 loc) · 802 Bytes
/
decorrelated.go
File metadata and controls
49 lines (43 loc) · 802 Bytes
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
package jitter
import (
"math/rand"
"sync"
"time"
)
type dcjTuple struct {
cntr int64
rng *rand.Rand
}
type Decorrelated struct {
New func() rand.Source64
Min, Max time.Duration
p sync.Pool
once sync.Once
}
func (j *Decorrelated) Apply(interval time.Duration) time.Duration {
j.once.Do(func() {
if j.New == nil {
j.New = func() rand.Source64 {
s := rand.NewSource(time.Now().UnixNano())
return any(s).(rand.Source64)
}
}
})
raw := j.p.Get()
if raw == nil {
raw = &dcjTuple{
cntr: int64(interval),
rng: rand.New(j.New()),
}
}
defer j.p.Put(raw)
t := raw.(*dcjTuple)
t.cntr = t.rng.Int63n(3 * t.cntr)
if t.cntr < int64(j.Min) {
t.cntr = int64(j.Min)
}
if t.cntr > int64(j.Max) {
t.cntr = int64(j.Max)
}
return time.Duration(t.cntr)
}