Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
1.9 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: Simple moving average class
  4. //
  5. // $NoKeywords: $
  6. //
  7. //
  8. //=============================================================================//
  9. #ifndef MOVING_AVERAGE_H
  10. #define MOVING_AVERAGE_H
  11. #ifdef _WIN32
  12. #pragma once
  13. #endif
  14. #include "tier0/platform.h"
  15. #include "tier0/basetypes.h"
  16. template<uint32 TBufferSize> class CUtlMovingAverage
  17. {
  18. public:
  19. CUtlMovingAverage() :
  20. m_nValuesPushed( 0 ),
  21. m_flTotal( 0.0f )
  22. {
  23. }
  24. void Reset()
  25. {
  26. m_nValuesPushed = 0;
  27. m_flTotal = 0.0f;
  28. }
  29. uint32 GetTotalValuesPushed() const
  30. {
  31. return m_nValuesPushed;
  32. }
  33. float GetAverage( )
  34. {
  35. uint n = MIN( TBufferSize, m_nValuesPushed );
  36. return n ? ( m_flTotal / static_cast<double>( n ) ) : 0.0f;
  37. }
  38. void GetAverageAndAbsRange( float *pflOutAverage, float *pflOutAbsRange, float *pflMinTime, float *pflMaxTime )
  39. {
  40. if ( m_nValuesPushed == 0 )
  41. {
  42. *pflOutAverage = 0;
  43. *pflOutAbsRange = 0;
  44. *pflMinTime = 0;
  45. *pflMaxTime = 0;
  46. return;
  47. }
  48. *pflOutAverage = GetAverage();
  49. const int nNumValues = MIN( m_nValuesPushed, TBufferSize );
  50. float flAbsRange = 0;
  51. float flMinTime = 9e+9;
  52. float flMaxTime = 0;
  53. for ( int i = 0; i < nNumValues; ++i )
  54. {
  55. float flDif = ( m_Buffer[i] - *pflOutAverage );
  56. flAbsRange = MAX( flAbsRange, abs( flDif ) );
  57. flMinTime = MIN( flMinTime, m_Buffer[i] );
  58. flMaxTime = MAX( flMaxTime, m_Buffer[i] );
  59. }
  60. *pflOutAbsRange = flAbsRange;
  61. *pflMinTime = flMinTime;
  62. *pflMaxTime = flMaxTime;
  63. }
  64. void PushValue( float v )
  65. {
  66. uint nIndex = m_nValuesPushed % TBufferSize;
  67. if ( m_nValuesPushed >= TBufferSize )
  68. {
  69. m_flTotal = MAX( m_flTotal - m_Buffer[nIndex], 0.0f );
  70. }
  71. m_flTotal += v;
  72. m_Buffer[nIndex] = v;
  73. m_nValuesPushed++;
  74. if ( UINT_MAX == m_nValuesPushed )
  75. {
  76. Reset();
  77. }
  78. }
  79. private:
  80. float m_Buffer[TBufferSize];
  81. uint32 m_nValuesPushed;
  82. double m_flTotal;
  83. };
  84. #endif // MOVING_AVERAGE_H