BoosterSeat  0.1
A C++ library that includes common utilities that are used in other projects.
rolling_average.hpp
Go to the documentation of this file.
1 #ifndef BST_ROLLING_AVERAGE_HPP_
2 #define BST_ROLLING_AVERAGE_HPP_
3 
4 #include <cstddef>
5 #include <queue>
6 
7 namespace bst {
8 
13 template <typename T = double>
15 public:
20  RollingAverage(size_t window_size) : window_size_(window_size) {
21  }
22 
26  ~RollingAverage() = default;
27 
34  void addValue(T value) {
35  queue_.push(value);
36  sum_ += value;
37 
38  if (queue_.size() > window_size_) {
39  sum_ -=
40  queue_.front(); // remove the oldest transaction count from the sum
41  queue_.pop(); // and the queue
42  }
43  }
44 
49  T getAverage() const {
50  if (queue_.empty()) {
51  return 0;
52  }
53 
54  return static_cast<T>(sum_ / queue_.size());
55  }
56 
62  void setWindowSize(size_t new_window_size) {
63  window_size_ = new_window_size;
64  while (queue_.size() > window_size_) {
65  sum_ -= queue_.front();
66  queue_.pop();
67  }
68  }
69 
73  void clear() {
74  queue_ = {};
75  sum_ = 0;
76  }
77 
83  size_t getNumElements() const {
84  return queue_.size();
85  }
86 
91  size_t getWindowSize() const {
92  return window_size_;
93  }
94 
99  void removeOldest() {
100  if (!queue_.empty()) {
101  sum_ -= queue_.front();
102  queue_.pop();
103  }
104  }
105 
106 private:
107  std::queue<T> queue_ = {};
108  size_t window_size_;
109  T sum_ = 0;
110 };
111 
112 } // namespace bst
113 
114 #endif /* ROLLING_AVERAGE_HPP_ */
Moving average calculator.
Definition: rolling_average.hpp:14
RollingAverage(size_t window_size)
Construct a RollingAverage object.
Definition: rolling_average.hpp:20
void removeOldest()
Remove the oldest element from the queue and update the sum. Safe to call if the queue is empty.
Definition: rolling_average.hpp:99
void clear()
Remove all elements from the queue and reset the sum to zero.
Definition: rolling_average.hpp:73
size_t window_size_
Definition: rolling_average.hpp:108
size_t getWindowSize() const
Get the window size.
Definition: rolling_average.hpp:91
T sum_
Definition: rolling_average.hpp:109
void addValue(T value)
Add a value to the rolling average. If the queue size exceeds the window size, the oldest value will ...
Definition: rolling_average.hpp:34
void setWindowSize(size_t new_window_size)
Set the window size. If the new window size is smaller than the current queue size,...
Definition: rolling_average.hpp:62
std::queue< T > queue_
Definition: rolling_average.hpp:107
T getAverage() const
This method returns the rolling average.
Definition: rolling_average.hpp:49
~RollingAverage()=default
Default destructor.
size_t getNumElements() const
Get the number of elements in the queue. This number may be less than the window size.
Definition: rolling_average.hpp:83
Definition: filesystem.cpp:34