64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package avgcachestate
|
|
|
|
import (
|
|
"s1d3sw1ped/SteamCache2/vfs/cachestate"
|
|
"sync"
|
|
)
|
|
|
|
// AvgCacheState is a cache state that averages the last N cache states.
|
|
type AvgCacheState struct {
|
|
size int
|
|
avgs []cachestate.CacheState
|
|
mu sync.Mutex
|
|
}
|
|
|
|
// New creates a new average cache state with the given size.
|
|
func New(size int) *AvgCacheState {
|
|
a := &AvgCacheState{
|
|
size: size,
|
|
avgs: make([]cachestate.CacheState, size),
|
|
mu: sync.Mutex{},
|
|
}
|
|
|
|
a.Clear()
|
|
|
|
return a
|
|
}
|
|
|
|
// Clear resets the average cache state to zero.
|
|
func (a *AvgCacheState) Clear() {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
for i := 0; i < len(a.avgs); i++ {
|
|
a.avgs[i] = cachestate.CacheStateMiss
|
|
}
|
|
}
|
|
|
|
// Add adds a cache state to the average cache state.
|
|
func (a *AvgCacheState) Add(cs cachestate.CacheState) {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
a.avgs = append(a.avgs, cs)
|
|
if len(a.avgs) > a.size {
|
|
a.avgs = a.avgs[1:]
|
|
}
|
|
}
|
|
|
|
// Avg returns the average cache state.
|
|
func (a *AvgCacheState) Avg() float64 {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
var hits int
|
|
|
|
for _, cs := range a.avgs {
|
|
if cs == cachestate.CacheStateHit {
|
|
hits++
|
|
}
|
|
}
|
|
|
|
return float64(hits) / float64(len(a.avgs))
|
|
}
|