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 constexpr explicit RateCounter(Rate desired) noexcept : val_(desired.value) {}
25 constexpr explicit RateCounter(Rate::ValueType desired) noexcept
26 : val_(desired) {}
27
28 RateCounter(const RateCounter& other) noexcept : val_(other.Load().value) {}
29
30 RateCounter& operator=(const RateCounter& other) noexcept {
31 if (this == &other) return *this;
32
33 Store(other.Load());
34 return *this;
35 }
36
37 RateCounter& operator=(Rate desired) noexcept {
38 Store(desired);
39 return *this;
40 }
41
42 void Store(Rate desired,
43 std::memory_order order = std::memory_order_relaxed) noexcept {
44 val_.store(desired.value, order);
45 }
46
47 Rate Load() const noexcept {
48 return Rate{val_.load(std::memory_order_relaxed)};
49 }
50
51 void Add(Rate arg,
52 std::memory_order order = std::memory_order_relaxed) noexcept {
53 val_.fetch_add(arg.value, order);
54 }
55
56 RateCounter& operator++() noexcept {
57 val_.fetch_add(1, std::memory_order_relaxed);
58 return *this;
59 }
60
61 Rate operator++(int) noexcept {
62 return Rate{val_.fetch_add(1, std::memory_order_relaxed)};
63 }
64
65 RateCounter& operator+=(Rate arg) noexcept {
66 val_.fetch_add(arg.value, std::memory_order_relaxed);
67 return *this;
68 }
69
70 RateCounter& operator+=(RateCounter arg) noexcept {
71 return *this += arg.Load();
72 }
73
74 private:
75 static_assert(std::atomic<Rate::ValueType>::is_always_lock_free);
76
77 std::atomic<Rate::ValueType> val_{0};
78};
79
80void DumpMetric(Writer& writer, const RateCounter& value);
81
82void ResetMetric(RateCounter& value);
83
84} // namespace utils::statistics
85
86USERVER_NAMESPACE_END