Skip to content

Commit

Permalink
Added variable latency delay, normal and uniform based
Browse files Browse the repository at this point in the history
  • Loading branch information
rikonor committed Jun 18, 2016
1 parent 2a3bba3 commit ca3a127
Showing 1 changed file with 51 additions and 2 deletions.
53 changes: 51 additions & 2 deletions thirdparty/delay/delay.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package delay

import (
"math/rand"
"sync"
"time"
)
Expand All @@ -23,8 +24,6 @@ type delay struct {
t time.Duration
}

// TODO func Variable(time.Duration) D returns a delay with probablistic latency

func (d *delay) Set(t time.Duration) time.Duration {
d.l.Lock()
defer d.l.Unlock()
Expand All @@ -44,3 +43,53 @@ func (d *delay) Get() time.Duration {
defer d.l.Unlock()
return d.t
}

// VariableNormal is a delay following a normal distribution
// Notice that to implement the D interface Set can only change the mean delay
// the standard deviation is set only at initialization
func VariableNormal(t, std time.Duration) D {
v := &variableNormal{
std: std,
rng: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))),
}
v.t = t
return v
}

type variableNormal struct {
delay
std time.Duration
rng *rand.Rand
}

func (d *variableNormal) Wait() {
d.l.RLock()
defer d.l.RUnlock()
randomDelay := time.Duration(d.rng.NormFloat64() * float64(d.std))
time.Sleep(randomDelay + d.t)
}

// VariableUniform is a delay following a uniform distribution
// Notice that to implement the D interface Set can only change the minimum delay
// the delta is set only at initialization
func VariableUniform(t, d time.Duration) D {
v := &variableUniform{
d: d,
rng: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))),
}
v.t = t
return v
}

type variableUniform struct {
delay
d time.Duration // max delta
rng *rand.Rand
}

func (d *variableUniform) Wait() {
d.l.RLock()
defer d.l.RUnlock()
randomDelay := time.Duration(d.rng.Float64() * float64(d.d))
time.Sleep(randomDelay + d.t)
}

1 comment on commit ca3a127

@GitCop
Copy link

@GitCop GitCop commented on ca3a127 Jun 18, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There were the following issues with your Pull Request

We ask for a few features in the commit message for Open Source licensing hygiene and commit message clarity.
git commit --amend can often help you quickly improve the commit message.
Guidelines and a script are available to help in the long run.
Your feedback on GitCop is welcome on this issue.


This message was auto-generated by https://gitcop.com

Please sign in to comment.