14 #ifndef hifi_SimpleMovingAverage_h
15 #define hifi_SimpleMovingAverage_h
21 class SimpleMovingAverage {
23 SimpleMovingAverage(
int numSamplesToAverage = 100);
24 SimpleMovingAverage(
const SimpleMovingAverage& other);
25 SimpleMovingAverage& operator=(
const SimpleMovingAverage& other);
27 int updateAverage(
float sample);
30 int getSampleCount()
const {
return _numSamples; };
31 float getAverage()
const {
return _average; };
32 float getEventDeltaAverage()
const;
33 float getAverageSampleValuePerSecond()
const {
return _average * (1.0f / getEventDeltaAverage()); }
35 uint64_t getUsecsSinceLastEvent()
const;
39 std::atomic<int> _numSamples;
40 std::atomic<uint64_t> _lastEventTimestamp;
41 std::atomic<float> _average;
42 std::atomic<float> _eventDeltaAverage;
45 float ONE_MINUS_WEIGHTING;
49 template <
class T,
int MAX_NUM_SAMPLES>
class MovingAverage {
52 MovingAverage(
const MovingAverage<T, MAX_NUM_SAMPLES>& other) {
55 MovingAverage<T, MAX_NUM_SAMPLES>& operator=(
const MovingAverage<T, MAX_NUM_SAMPLES>& other) {
56 numSamples = (int)other.numSamples;
57 average = (T)other.average;
61 const float WEIGHTING = 1.0f / (float)MAX_NUM_SAMPLES;
62 const float ONE_MINUS_WEIGHTING = 1.0f - WEIGHTING;
63 std::atomic<int> numSamples{ 0 };
64 std::atomic<T> average;
70 bool isAverageValid()
const {
return (numSamples > 0); }
72 void addSample(T sample) {
74 average = (sample * (T)WEIGHTING) + (average * (T)ONE_MINUS_WEIGHTING);
82 template <
class T,
int MAX_NUM_SAMPLES>
class ThreadSafeMovingAverage {
85 std::unique_lock<std::mutex> lock(_lock);
89 bool isAverageValid()
const {
90 std::unique_lock<std::mutex> lock(_lock);
91 return (_samples > 0);
94 void addSample(T sample) {
95 std::unique_lock<std::mutex> lock(_lock);
97 _average = (sample * WEIGHTING) + (_average * ONE_MINUS_WEIGHTING);
104 T getAverage()
const {
105 std::unique_lock<std::mutex> lock(_lock);
109 size_t getSamples()
const {
110 std::unique_lock<std::mutex> lock(_lock);
115 const float WEIGHTING = 1.0f / (float)MAX_NUM_SAMPLES;
116 const float ONE_MINUS_WEIGHTING = 1.0f - WEIGHTING;
117 size_t _samples { 0 };
119 mutable std::mutex _lock;