DUNE-DAQ
DUNE Trigger and Data Acquisition software
Loading...
Searching...
No Matches
RateLimiter.hpp
Go to the documentation of this file.
1
8#ifndef DATAHANDLINGLIBS_INCLUDE_DATAHANDLINGLIBS_UTILS_RATELIMITER_HPP_
9#define DATAHANDLINGLIBS_INCLUDE_DATAHANDLINGLIBS_UTILS_RATELIMITER_HPP_
10
11#include <atomic>
12#include <chrono>
13#include <ctime>
14#include <unistd.h>
15
16namespace dunedaq {
17namespace datahandlinglibs {
18
35{
36public:
37 using timestamp_t = std::uint64_t; // NOLINT(build/unsigned)
38 static inline constexpr timestamp_t ns = 1;
39 static inline constexpr timestamp_t us = 1000 * ns;
40 static inline constexpr timestamp_t ms = 1000 * us;
41 static inline constexpr timestamp_t s = 1000 * ms;
42
43 explicit RateLimiter(double kilohertz)
44 : m_max_overshoot(10 * ms)
45 {
46 adjust(kilohertz);
47 init();
48 }
49
50 void init()
51 {
52 m_now = gettime();
53 m_deadline = m_now + m_period.load();
54 }
55
67 void adjust(double kilohertz)
68 {
69 m_kilohertz.store(kilohertz);
70 m_period.store(static_cast<timestamp_t>((1000.f / m_kilohertz) * static_cast<double>(us)));
71 }
72
73 void limit()
74 {
75 m_now = gettime();
77 m_deadline = m_now + m_period.load();
78 } else {
79 if (m_now < m_deadline) {
80 if (m_deadline - m_now > 0) {
81 timespec tim;
82 tim.tv_sec = 0;
83 tim.tv_nsec = m_deadline - m_now;
84 // The second argument will be overwritten but we
85 // do not care about this temporary variable
86 nanosleep(&tim, &tim);
87 m_now = gettime();
88 }
89 while (m_now < m_deadline) {
90 m_now = gettime();
91 }
92 }
93 m_deadline += m_period.load();
94 }
95 }
96
97protected:
99 {
100 ::timespec ts;
101 ::clock_gettime(CLOCK_MONOTONIC, &ts);
102 return timestamp_t(ts.tv_sec) * s + timestamp_t(ts.tv_nsec) * ns;
103 }
104
105private:
106 std::atomic<double> m_kilohertz;
108 std::atomic<timestamp_t> m_period;
111};
112
113} // namespace datahandlinglibs
114} // namespace dunedaq
115
116#endif // DATAHANDLINGLIBS_INCLUDE_DATAHANDLINGLIBS_UTILS_RATELIMITER_HPP_
std::atomic< timestamp_t > m_period
static constexpr timestamp_t us
static constexpr timestamp_t s
static constexpr timestamp_t ms
static constexpr timestamp_t ns
Including Qt Headers.
PDS Frame with unphysical timestamp detected with ts