performanceTimer.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package utils
  2. import (
  3. "sort"
  4. "sync"
  5. "time"
  6. )
  7. var l = sync.Mutex{}
  8. // The "start" timestamp of a timing event.
  9. var _pointsInTime = make(map[string]time.Time)
  10. // A collection of timestamp durations for returning the average of.
  11. var _durationStorage = make(map[string][]float64)
  12. // StartPerformanceMonitor will keep track of the start time of this event.
  13. func StartPerformanceMonitor(key string) {
  14. l.Lock()
  15. if len(_durationStorage[key]) > 20 {
  16. _durationStorage[key] = removeHighValue(_durationStorage[key])
  17. }
  18. _pointsInTime[key] = time.Now()
  19. l.Unlock()
  20. }
  21. // GetAveragePerformance will return the average durations for the event.
  22. func GetAveragePerformance(key string) float64 {
  23. timestamp := _pointsInTime[key]
  24. if timestamp.IsZero() {
  25. return 0
  26. }
  27. l.Lock()
  28. defer l.Unlock()
  29. delta := time.Since(timestamp).Seconds()
  30. _durationStorage[key] = append(_durationStorage[key], delta)
  31. if len(_durationStorage[key]) < 8 {
  32. return 0
  33. }
  34. _durationStorage[key] = removeHighValue(_durationStorage[key])
  35. return avg(_durationStorage[key])
  36. }
  37. func removeHighValue(values []float64) []float64 {
  38. sort.Float64s(values)
  39. return values[:len(values)-1]
  40. }
  41. func avg(values []float64) float64 {
  42. total := 0.0
  43. for _, number := range values {
  44. total += number
  45. }
  46. average := total / float64(len(values))
  47. return average
  48. }