fix: track cache hits and misses in average cache state
This commit is contained in:
@@ -7,9 +7,11 @@ import (
|
|||||||
|
|
||||||
// AvgCacheState is a cache state that averages the last N cache states.
|
// AvgCacheState is a cache state that averages the last N cache states.
|
||||||
type AvgCacheState struct {
|
type AvgCacheState struct {
|
||||||
size int
|
size int
|
||||||
avgs []cachestate.CacheState
|
hits int
|
||||||
mu sync.Mutex
|
misses int
|
||||||
|
avgs []cachestate.CacheState
|
||||||
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new average cache state with the given size.
|
// New creates a new average cache state with the given size.
|
||||||
@@ -42,8 +44,21 @@ func (a *AvgCacheState) Add(cs cachestate.CacheState) {
|
|||||||
|
|
||||||
a.avgs = append(a.avgs, cs)
|
a.avgs = append(a.avgs, cs)
|
||||||
if len(a.avgs) > a.size {
|
if len(a.avgs) > a.size {
|
||||||
|
switch a.avgs[0] {
|
||||||
|
case cachestate.CacheStateHit:
|
||||||
|
a.hits--
|
||||||
|
case cachestate.CacheStateMiss:
|
||||||
|
a.misses--
|
||||||
|
}
|
||||||
a.avgs = a.avgs[1:]
|
a.avgs = a.avgs[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch cs {
|
||||||
|
case cachestate.CacheStateHit:
|
||||||
|
a.hits++
|
||||||
|
case cachestate.CacheStateMiss:
|
||||||
|
a.misses++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Avg returns the average cache state.
|
// Avg returns the average cache state.
|
||||||
@@ -51,13 +66,5 @@ func (a *AvgCacheState) Avg() float64 {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
var hits int
|
return float64(a.hits) / (float64(a.misses) + 0.0000001)
|
||||||
for _, cs := range a.avgs {
|
|
||||||
switch cs {
|
|
||||||
case cachestate.CacheStateHit:
|
|
||||||
hits++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return float64(hits) / float64(len(a.avgs))
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user