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 RateCounter& operator++() noexcept {
59 val_.fetch_add(1, std::memory_order_relaxed);
60 return *this;
61 }
62
63 Rate operator++(int) noexcept {
64 return Rate{val_.fetch_add(1, std::memory_order_relaxed)};
65 }
66
67 RateCounter& operator+=(Rate arg) noexcept {
68 val_.fetch_add(arg.value, std::memory_order_relaxed);
69 return *this;
70 }
71
72 RateCounter& operator+=(const RateCounter& arg) noexcept {
73 *this += arg.Load();
74 return *this;
75 }
76
77 private:
78 static_assert(std::atomic<Rate::ValueType>::is_always_lock_free);
79
80 std::atomic<Rate::ValueType> val_{0};
81};
82
83void DumpMetric(Writer& writer, const RateCounter& value);
84
85void ResetMetric(RateCounter& value);
86
87} // namespace utils::statistics
88
89USERVER_NAMESPACE_END