From 9c02c39487d9b408e5c8b139b3b701ef96bc9f9b Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Thu, 20 Oct 2022 08:42:41 +0300 Subject: [PATCH] lib/workingsetcache: randomize interval for swapping curr and prev caches This should make CPU usage smoother over time, since different caches will be swapped at different times. --- lib/workingsetcache/cache.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/workingsetcache/cache.go b/lib/workingsetcache/cache.go index 8c4c220b0..1045db821 100644 --- a/lib/workingsetcache/cache.go +++ b/lib/workingsetcache/cache.go @@ -129,7 +129,8 @@ func (c *Cache) runWatchers(expireDuration time.Duration) { } func (c *Cache) expirationWatcher(expireDuration time.Duration) { - t := time.NewTicker(expireDuration / 2) + expireDuration += timeJitter(expireDuration / 10) + t := time.NewTicker(expireDuration) for { select { case <-c.stopCh: @@ -155,7 +156,9 @@ func (c *Cache) expirationWatcher(expireDuration time.Duration) { } func (c *Cache) cacheSizeWatcher() { - t := time.NewTicker(1500 * time.Millisecond) + checkInterval := 1500 * time.Millisecond + checkInterval += timeJitter(checkInterval / 10) + t := time.NewTicker(checkInterval) defer t.Stop() var maxBytesSize uint64 @@ -375,3 +378,8 @@ func (c *Cache) SetBig(key, value []byte) { curr := c.curr.Load().(*fastcache.Cache) curr.SetBig(key, value) } + +func timeJitter(d time.Duration) time.Duration { + n := float64(time.Now().UnixNano()%1e9) / 1e9 + return time.Duration(float64(d) * n) +}