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
5
6#include <algorithm>
7#include <numeric>
8
11
12USERVER_NAMESPACE_BEGIN
13
14namespace utils {
15
26template <typename T>
27class SlidingInterval final {
28public:
30 explicit SlidingInterval(std::size_t window_size)
31 : buckets_(window_size)
32 {
33 UASSERT(this->buckets_.size() > 0);
34 }
35
38 void Update(T value) {
39 buckets_[idx_] = value;
40 ++idx_;
41 if (idx_ == buckets_.size()) {
42 idx_ = 0;
43 }
44 }
45
49 [[nodiscard]] T GetSmoothed() const {
50 return std::accumulate(buckets_.begin(), buckets_.end(), static_cast<T>(0)) / this->buckets_.size();
51 }
52
56 [[nodiscard]] T GetMinimal() const { return *std::ranges::min_element(buckets_); }
57
61 [[nodiscard]] T GetMaximum() const { return *std::ranges::max_element(buckets_); }
62
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