Skip to content

Commit ca3a127

Browse files
committed
Added variable latency delay, normal and uniform based
1 parent 2a3bba3 commit ca3a127

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed

thirdparty/delay/delay.go

+51-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package delay
22

33
import (
4+
"math/rand"
45
"sync"
56
"time"
67
)
@@ -23,8 +24,6 @@ type delay struct {
2324
t time.Duration
2425
}
2526

26-
// TODO func Variable(time.Duration) D returns a delay with probablistic latency
27-
2827
func (d *delay) Set(t time.Duration) time.Duration {
2928
d.l.Lock()
3029
defer d.l.Unlock()
@@ -44,3 +43,53 @@ func (d *delay) Get() time.Duration {
4443
defer d.l.Unlock()
4544
return d.t
4645
}
46+
47+
// VariableNormal is a delay following a normal distribution
48+
// Notice that to implement the D interface Set can only change the mean delay
49+
// the standard deviation is set only at initialization
50+
func VariableNormal(t, std time.Duration) D {
51+
v := &variableNormal{
52+
std: std,
53+
rng: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))),
54+
}
55+
v.t = t
56+
return v
57+
}
58+
59+
type variableNormal struct {
60+
delay
61+
std time.Duration
62+
rng *rand.Rand
63+
}
64+
65+
func (d *variableNormal) Wait() {
66+
d.l.RLock()
67+
defer d.l.RUnlock()
68+
randomDelay := time.Duration(d.rng.NormFloat64() * float64(d.std))
69+
time.Sleep(randomDelay + d.t)
70+
}
71+
72+
// VariableUniform is a delay following a uniform distribution
73+
// Notice that to implement the D interface Set can only change the minimum delay
74+
// the delta is set only at initialization
75+
func VariableUniform(t, d time.Duration) D {
76+
v := &variableUniform{
77+
d: d,
78+
rng: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))),
79+
}
80+
v.t = t
81+
return v
82+
}
83+
84+
type variableUniform struct {
85+
delay
86+
d time.Duration // max delta
87+
rng *rand.Rand
88+
}
89+
90+
func (d *variableUniform) Wait() {
91+
d.l.RLock()
92+
defer d.l.RUnlock()
93+
randomDelay := time.Duration(d.rng.Float64() * float64(d.d))
94+
time.Sleep(randomDelay + d.t)
95+
}

0 commit comments

Comments
 (0)