Branch data Line data Source code
1 : : #ifndef RATEMONITOR_H
2 : : #define RATEMONITOR_H
3 : :
4 : : #include <chrono>
5 : : #include <atomic>
6 : :
7 : : /**
8 : : * @brief Simple utility to monitor event frequency (Hz) over a 1-second sliding window.
9 : : */
10 : : class RateMonitor {
11 : : public:
12 : 292 : RateMonitor() : m_count(0), m_lastRateScaled(0) {
13 : 292 : m_startTime = std::chrono::steady_clock::now();
14 : 292 : }
15 : :
16 : : /**
17 : : * @brief Record a single event occurrence.
18 : : */
19 : 5796 : void RecordEvent() {
20 : 5796 : RecordEventAt(std::chrono::steady_clock::now());
21 : 5796 : }
22 : :
23 : : /**
24 : : * @brief Record an event at a specific time (useful for testing).
25 : : */
26 : 6304 : void RecordEventAt(std::chrono::steady_clock::time_point now) {
27 : 6304 : m_count++;
28 [ + - + - ]: 6304 : auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_startTime).count();
29 : :
30 : : // Update rate every second
31 [ + + ]: 6304 : if (duration_ms >= 1000) {
32 : 16 : long count = m_count.exchange(0);
33 : 16 : double rate = (double)count * 1000.0 / (double)duration_ms;
34 : 16 : m_lastRateScaled.store((long)(rate * 100.0));
35 : 16 : m_startTime = now;
36 : : }
37 : 6304 : }
38 : :
39 : : /**
40 : : * @brief Get the last calculated rate in Hz.
41 : : */
42 : 38095 : double GetRate() const {
43 : 76190 : return (double)m_lastRateScaled.load() / 100.0;
44 : : }
45 : :
46 : : private:
47 : : std::atomic<long> m_count;
48 : : std::chrono::steady_clock::time_point m_startTime;
49 : : std::atomic<long> m_lastRateScaled; // Rate multiplied by 100 for atomic storage
50 : : };
51 : :
52 : : #endif // RATEMONITOR_H
|