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) : buckets_(window_size) { UASSERT(this->buckets_.size() > 0); }
31
32 /// @brief replaces the oldest value in interval with `value`, i.e slides the
33 /// interval.
34 void Update(T value) {
35 buckets_[idx_] = value;
36 ++idx_;
37 if (idx_ == buckets_.size()) {
38 idx_ = 0;
39 }
40 }
41
42 /// @returns Average value in the interval
43 ///
44 /// \b Complexity: O(window_size)
45 [[nodiscard]] T GetSmoothed() const {
46 return std::accumulate(buckets_.begin(), buckets_.end(), static_cast<T>(0)) / this->buckets_.size();
47 }
48
49 /// @returns Minimal value in the interval
50 ///
51 /// \b Complexity: O(window_size)
52 [[nodiscard]] T GetMinimal() const { return *std::min_element(buckets_.begin(), buckets_.end()); }
53
54 /// @returns Maximum value in the interval
55 ///
56 /// \b Complexity: O(window_size)
57 [[nodiscard]] T GetMaximum() const { return *std::max_element(buckets_.begin(), buckets_.end()); }
58
59 /// @returns Elements count in the interval, i.e. `window_size` passed to
60 /// constructor.
61 [[nodiscard]] std::size_t GetWindowSize() const { return buckets_.size(); }
62
63private:
64 utils::FixedArray<T> buckets_;
65 std::size_t idx_{0};
66};
67
68} // namespace utils
69
70USERVER_NAMESPACE_END