2020-10-15 00:07:38 +03:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sort"
|
2021-01-05 08:18:35 +03:00
|
|
|
"sync"
|
2020-10-15 00:07:38 +03:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-01-05 08:18:35 +03:00
|
|
|
var l = sync.Mutex{}
|
|
|
|
|
2020-11-13 02:14:59 +03:00
|
|
|
// The "start" timestamp of a timing event.
|
2020-10-15 00:07:38 +03:00
|
|
|
var _pointsInTime = make(map[string]time.Time)
|
|
|
|
|
2020-11-13 02:14:59 +03:00
|
|
|
// A collection of timestamp durations for returning the average of.
|
2020-10-15 00:07:38 +03:00
|
|
|
var _durationStorage = make(map[string][]float64)
|
|
|
|
|
2020-11-13 02:14:59 +03:00
|
|
|
// StartPerformanceMonitor will keep track of the start time of this event.
|
2020-10-15 00:07:38 +03:00
|
|
|
func StartPerformanceMonitor(key string) {
|
2021-01-05 08:18:35 +03:00
|
|
|
l.Lock()
|
2020-11-17 08:02:48 +03:00
|
|
|
if len(_durationStorage[key]) > 20 {
|
|
|
|
_durationStorage[key] = removeHighValue(_durationStorage[key])
|
2020-10-15 00:07:38 +03:00
|
|
|
}
|
|
|
|
_pointsInTime[key] = time.Now()
|
2021-01-05 08:18:35 +03:00
|
|
|
l.Unlock()
|
2020-10-15 00:07:38 +03:00
|
|
|
}
|
|
|
|
|
2020-11-13 02:14:59 +03:00
|
|
|
// GetAveragePerformance will return the average durations for the event.
|
2020-10-15 00:07:38 +03:00
|
|
|
func GetAveragePerformance(key string) float64 {
|
|
|
|
timestamp := _pointsInTime[key]
|
|
|
|
if timestamp.IsZero() {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2021-01-05 08:18:35 +03:00
|
|
|
l.Lock()
|
2021-01-05 09:02:16 +03:00
|
|
|
defer l.Unlock()
|
|
|
|
|
2020-10-15 00:07:38 +03:00
|
|
|
delta := time.Since(timestamp).Seconds()
|
|
|
|
_durationStorage[key] = append(_durationStorage[key], delta)
|
2020-11-17 08:02:48 +03:00
|
|
|
if len(_durationStorage[key]) < 8 {
|
2020-10-15 00:07:38 +03:00
|
|
|
return 0
|
|
|
|
}
|
2020-11-17 08:02:48 +03:00
|
|
|
_durationStorage[key] = removeHighValue(_durationStorage[key])
|
2021-01-05 08:18:35 +03:00
|
|
|
|
2020-10-15 00:07:38 +03:00
|
|
|
return avg(_durationStorage[key])
|
|
|
|
}
|
|
|
|
|
2020-11-17 08:02:48 +03:00
|
|
|
func removeHighValue(values []float64) []float64 {
|
2020-10-15 00:07:38 +03:00
|
|
|
sort.Float64s(values)
|
2020-11-17 08:02:48 +03:00
|
|
|
return values[:len(values)-1]
|
2020-10-15 00:07:38 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func avg(values []float64) float64 {
|
|
|
|
total := 0.0
|
|
|
|
for _, number := range values {
|
|
|
|
total = total + number
|
|
|
|
}
|
|
|
|
average := total / float64(len(values))
|
|
|
|
return average
|
|
|
|
}
|