1
1
package delay
2
2
3
3
import (
4
+ "math/rand"
4
5
"sync"
5
6
"time"
6
7
)
@@ -23,8 +24,6 @@ type delay struct {
23
24
t time.Duration
24
25
}
25
26
26
- // TODO func Variable(time.Duration) D returns a delay with probablistic latency
27
-
28
27
func (d * delay ) Set (t time.Duration ) time.Duration {
29
28
d .l .Lock ()
30
29
defer d .l .Unlock ()
@@ -44,3 +43,53 @@ func (d *delay) Get() time.Duration {
44
43
defer d .l .Unlock ()
45
44
return d .t
46
45
}
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