userver: userver/utils/sliding_interval.hpp Source File
Loading...
Searching...
No Matches
sliding_interval.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/sliding_interval.hpp
4/// @brief @copybrief utils::SlidingInterval
5
6#include <algorithm>
7#include <numeric>
8
9#include <userver/utils/assert.hpp>
10#include <userver/utils/fixed_array.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace utils {
15
16/// @ingroup userver_universal userver_containers
17///
18/// @brief Sliding interval of values that provides functions to compute
19/// average, min and max values from the last `window_size` values of interval.
20///
21/// It fits for small `window_size` values because has O(window_size) complexity
22/// on most operations.
23///
24/// @see utils::statistics::MinMaxAvg for a concurrent safe computation over
25/// a whole measurement interval.
26template <typename T>
27class SlidingInterval final {
28public:
29 /// @brief Create a SlidingInterval of `window_size` values
30 explicit SlidingInterval(std::size_t window_size)
31 : buckets_(window_size)
32 {
33 UASSERT(this->buckets_.size() > 0);
34 }
35
36 /// @brief replaces the oldest value in interval with `value`, i.e slides the
37 /// interval.
38 void Update(T value) {
39 buckets_[idx_] = value;
40 ++idx_;
41 if (idx_ == buckets_.size()) {
42 idx_ = 0;
43 }
44 }
45
46 /// @returns Average value in the interval
47 ///
48 /// \b Complexity: O(window_size)
49 [[nodiscard]] T GetSmoothed() const {
50 return std::accumulate(buckets_.begin(), buckets_.end(), static_cast<T>(0)) / this->buckets_.size();
51 }
52
53 /// @returns Minimal value in the interval
54 ///
55 /// \b Complexity: O(window_size)
56 [[nodiscard]] T GetMinimal() const { return *std::min_element(buckets_.begin(), buckets_.end()); }
57
58 /// @returns Maximum value in the interval
59 ///
60 /// \b Complexity: O(window_size)
61 [[nodiscard]] T GetMaximum() const { return *std::max_element(buckets_.begin(), buckets_.end()); }
62
63 /// @returns Elements count in the interval, i.e. `window_size` passed to
64 /// constructor.
65 [[nodiscard]] std::size_t GetWindowSize() const { return buckets_.size(); }
66
67private:
68 utils::FixedArray<T> buckets_;
69 std::size_t idx_{0};
70};
71
72} // namespace utils
73
74USERVER_NAMESPACE_END