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 {
20public:
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 : val_(desired) {}
28
29 RateCounter(const RateCounter& other) noexcept : val_(other.Load().value) {}
30
31 RateCounter& operator=(const RateCounter& other) noexcept {
32 if (this == &other) return *this;
33
34 Store(other.Load());
35 return *this;
36 }
37
38 RateCounter& operator=(Rate desired) noexcept {
39 Store(desired);
40 return *this;
41 }
42
43 void Store(Rate desired, std::memory_order order = std::memory_order_relaxed) noexcept {
44 val_.store(desired.value, order);
45 }
46
47 Rate Load() const noexcept { return Rate{val_.load(std::memory_order_relaxed)}; }
48
49 void Add(Rate arg, std::memory_order order = std::memory_order_relaxed) noexcept {
50 val_.fetch_add(arg.value, order);
51 }
52
53 void AddAsSingleProducer(Rate arg) noexcept {
54 val_.store(val_.load(std::memory_order_relaxed) + arg.value, std::memory_order_relaxed);
55 }
56
57 RateCounter& operator++() noexcept {
58 val_.fetch_add(1, std::memory_order_relaxed);
59 return *this;
60 }
61
62 Rate operator++(int) noexcept { return Rate{val_.fetch_add(1, std::memory_order_relaxed)}; }
63
64 RateCounter& operator+=(Rate arg) noexcept {
65 val_.fetch_add(arg.value, std::memory_order_relaxed);
66 return *this;
67 }
68
69 RateCounter& operator+=(const RateCounter& arg) noexcept {
70 *this += arg.Load();
71 return *this;
72 }
73
74private:
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