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