improving the concurrency performance of random value calculation
This commit is contained in:
parent
4f8e984df6
commit
6edee6c9c9
22
client/cache/random_expired_cache.go
vendored
22
client/cache/random_expired_cache.go
vendored
@ -17,6 +17,7 @@ package cache
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -44,12 +45,25 @@ func NewRandomExpireCache(adapter Cache, opts ...RandomExpireCacheOption) Cache
|
||||
fn(&rec)
|
||||
}
|
||||
if rec.Offset == nil {
|
||||
rec.Offset = defaultExpiredFunc
|
||||
rec.Offset = defaultExpiredFunc()
|
||||
}
|
||||
return &rec
|
||||
}
|
||||
|
||||
// defaultExpiredFunc genreate random time offset expired
|
||||
func defaultExpiredFunc() time.Duration {
|
||||
return time.Duration(rand.Intn(5)+3) * time.Second
|
||||
// defaultExpiredFunc return a func that used to generate random time offset (range: [3s,8s)) expired
|
||||
func defaultExpiredFunc() func() time.Duration {
|
||||
const size = 5
|
||||
var randTimes [size]time.Duration
|
||||
for i := range randTimes {
|
||||
randTimes[i] = time.Duration(i + 3)
|
||||
}
|
||||
// shuffle values
|
||||
for i := range randTimes {
|
||||
n := rand.Intn(size)
|
||||
randTimes[i], randTimes[n] = randTimes[n], randTimes[i]
|
||||
}
|
||||
var i uint64
|
||||
return func() time.Duration {
|
||||
return randTimes[atomic.AddUint64(&i, 1)%size]
|
||||
}
|
||||
}
|
||||
|
||||
2
client/cache/random_expired_cache_test.go
vendored
2
client/cache/random_expired_cache_test.go
vendored
@ -29,7 +29,7 @@ func TestRandomExpireCache(t *testing.T) {
|
||||
|
||||
// cache := NewRandomExpireCache(bm)
|
||||
cache := NewRandomExpireCache(bm, func(opt *RandomExpireCache) {
|
||||
opt.offset = defaultExpiredFunc
|
||||
opt.Offset = defaultExpiredFunc()
|
||||
})
|
||||
|
||||
timeoutDuration := 3 * time.Second
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user