userver: userver/utils/statistics/rate_counter.hpp Source File
Loading...
Searching...
No Matches
rate_counter.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/statistics/rate_counter.hpp
4/// @brief @copybrief utils::statistics::RateCounter
5
6#include <atomic>
7
8#include <userver/utils/statistics/fwd.hpp>
9#include <userver/utils/statistics/rate.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utils::statistics {
14
15/// @brief Atomic counter of type Rate with relaxed memory ordering
16///
17/// This class is represented as Rate metric when serializing to statistics.
18/// Otherwise it is the same class as RelaxedCounter
19class RateCounter final {
20 public:
21 using ValueType = Rate;
22
23 constexpr RateCounter() noexcept = default;
24
25 constexpr explicit RateCounter(Rate desired) noexcept : val_(desired.value) {}
26
27 constexpr explicit RateCounter(Rate::ValueType desired) noexcept
28 : val_(desired) {}
29
30 RateCounter(const RateCounter& other) noexcept : val_(other.Load().value) {}
31
32 RateCounter& operator=(const RateCounter& other) noexcept {
33 if (this == &other) return *this;
34
35 Store(other.Load());
36 return *this;
37 }
38
39 RateCounter& operator=(Rate desired) noexcept {
40 Store(desired);
41 return *this;
42 }
43
44 void Store(Rate desired,
45 std::memory_order order = std::memory_order_relaxed) noexcept {
46 val_.store(desired.value, order);
47 }
48
49 Rate Load() const noexcept {
50 return Rate{val_.load(std::memory_order_relaxed)};
51 }
52
53 void Add(Rate arg,
54 std::memory_order order = std::memory_order_relaxed) noexcept {
55 val_.fetch_add(arg.value, order);
56 }
57
58 void AddAsSingleProducer(Rate arg) noexcept {
59 val_.store(val_.load(std::memory_order_relaxed) + arg.value,
60 std::memory_order_relaxed);
61 }
62
63 RateCounter& operator++() noexcept {
64 val_.fetch_add(1, std::memory_order_relaxed);
65 return *this;
66 }
67
68 Rate operator++(int) noexcept {
69 return Rate{val_.fetch_add(1, std::memory_order_relaxed)};
70 }
71
72 RateCounter& operator+=(Rate arg) noexcept {
73 val_.fetch_add(arg.value, std::memory_order_relaxed);
74 return *this;
75 }
76
77 RateCounter& operator+=(const RateCounter& arg) noexcept {
78 *this += arg.Load();
79 return *this;
80 }
81
82 private:
83 static_assert(std::atomic<Rate::ValueType>::is_always_lock_free);
84
85 std::atomic<Rate::ValueType> val_{0};
86};
87
88void DumpMetric(Writer& writer, const RateCounter& value);
89
90void ResetMetric(RateCounter& value);
91
92} // namespace utils::statistics
93
94USERVER_NAMESPACE_END