forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unstable.go
41 lines (36 loc) · 787 Bytes
/
unstable.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
package mathx
import (
"math/rand"
"sync"
"time"
)
type Unstable struct {
deviation float64
r *rand.Rand
lock *sync.Mutex
}
func NewUnstable(deviation float64) Unstable {
if deviation < 0 {
deviation = 0
}
if deviation > 1 {
deviation = 1
}
return Unstable{
deviation: deviation,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
}
}
func (u Unstable) AroundDuration(base time.Duration) time.Duration {
u.lock.Lock()
val := time.Duration((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}
func (u Unstable) AroundInt(base int64) int64 {
u.lock.Lock()
val := int64((1 + u.deviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}