improving the concurrency performance of random value calculation

This commit is contained in:
kevinzeng 2022-06-28 13:17:48 +08:00
parent 4f8e984df6
commit 6edee6c9c9
2 changed files with 19 additions and 5 deletions

View File

@ -17,6 +17,7 @@ package cache
import ( import (
"context" "context"
"math/rand" "math/rand"
"sync/atomic"
"time" "time"
) )
@ -44,12 +45,25 @@ func NewRandomExpireCache(adapter Cache, opts ...RandomExpireCacheOption) Cache
fn(&rec) fn(&rec)
} }
if rec.Offset == nil { if rec.Offset == nil {
rec.Offset = defaultExpiredFunc rec.Offset = defaultExpiredFunc()
} }
return &rec return &rec
} }
// defaultExpiredFunc genreate random time offset expired // defaultExpiredFunc return a func that used to generate random time offset (range: [3s,8s)) expired
func defaultExpiredFunc() time.Duration { func defaultExpiredFunc() func() time.Duration {
return time.Duration(rand.Intn(5)+3) * time.Second 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]
}
} }

View File

@ -29,7 +29,7 @@ func TestRandomExpireCache(t *testing.T) {
// cache := NewRandomExpireCache(bm) // cache := NewRandomExpireCache(bm)
cache := NewRandomExpireCache(bm, func(opt *RandomExpireCache) { cache := NewRandomExpireCache(bm, func(opt *RandomExpireCache) {
opt.offset = defaultExpiredFunc opt.Offset = defaultExpiredFunc()
}) })
timeoutDuration := 3 * time.Second timeoutDuration := 3 * time.Second