stats.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package stats
  2. import (
  3. "github.com/g3n/engine/gls"
  4. "runtime"
  5. "time"
  6. )
  7. // Stats contains several statistics usefull for performance evaluation
  8. type Stats struct {
  9. Glstats gls.Stats // GLS statistics structure
  10. UnilocHits int // Uniform location cache hits per frame
  11. UnilocMiss int // Uniform location cache misses per frame
  12. Unisets int // Uniform sets per frame
  13. Drawcalls int // Draw calls per frame
  14. Cgocalls int // Cgo calls per frame
  15. gs *gls.GLS // reference to gls state
  16. glprev gls.Stats // previous gls statistics
  17. frames int // frame counter
  18. cgocalls int64 // previous number of cgo calls
  19. last time.Time // last update time
  20. }
  21. // NewStats creates and returns a pointer to a new statistics object
  22. func NewStats(gs *gls.GLS) *Stats {
  23. s := new(Stats)
  24. s.gs = gs
  25. s.last = time.Now()
  26. return s
  27. }
  28. // Update should be called in the render loop with the desired update interval.
  29. // Returns true when the interval has elapsed and the statistics has been updated.
  30. func (s *Stats) Update(d time.Duration) bool {
  31. // If the specified time duration has not elapsed from previous update,
  32. // nothing to do.
  33. now := time.Now()
  34. s.frames++
  35. if s.last.Add(d).After(now) {
  36. return false
  37. }
  38. // Update GLS statistics
  39. s.gs.Stats(&s.Glstats)
  40. // Calculates uniform location cache hits per frame
  41. unilochits := s.Glstats.UnilocHits - s.glprev.UnilocHits
  42. s.UnilocHits = int(float64(unilochits) / float64(s.frames))
  43. // Calculates uniform location cache hits per frame
  44. unilocmiss := s.Glstats.UnilocMiss - s.glprev.UnilocMiss
  45. s.UnilocMiss = int(float64(unilocmiss) / float64(s.frames))
  46. // Calculates uniforms sets per frame
  47. unisets := s.Glstats.Unisets - s.glprev.Unisets
  48. s.Unisets = int(float64(unisets) / float64(s.frames))
  49. // Calculates draw calls per frame
  50. drawcalls := s.Glstats.Drawcalls - s.glprev.Drawcalls
  51. s.Drawcalls = int(float64(drawcalls) / float64(s.frames))
  52. // Calculates number of cgo calls per frame
  53. current := runtime.NumCgoCall()
  54. cgocalls := current - s.cgocalls
  55. s.Cgocalls = int(float64(cgocalls) / float64(s.frames))
  56. s.cgocalls = current
  57. s.glprev = s.Glstats
  58. s.last = now
  59. s.frames = 0
  60. return true
  61. }