Motion Master
Loading...
Searching...
No Matches
main_timer.h
Go to the documentation of this file.
1#pragma once
2
3#ifdef _WIN32
4#include <windows.h> // Must be included before mmsystem.h for Windows multimedia timer
5#endif
6#ifdef __linux__
7#include <signal.h> // POSIX signal handling
8#include <time.h> // POSIX timer and time functions
9#endif
10
11#ifdef _WIN32
12#include <mmsystem.h> // Windows multimedia system for timeSetEvent
13#endif
14
15#include <atomic>
16#include <chrono>
17#include <condition_variable>
18#include <mutex>
19
32class MainTimer {
33 public:
37 static unsigned int DELAY;
38
43 static std::condition_variable cv;
44
53 static MainTimer& getInstance();
54
61 static void notifyAllListeners();
62
69 void wait();
70
79 uint64_t getTickCount() const;
80
88 uint64_t getCycleCount() const;
89
97 uint64_t getCycleMissedTickCount() const;
98
106 int64_t getElapsedTime() const;
107
108 private:
110 std::mutex mx_;
111
113 std::condition_variable cv_;
114
116 unsigned int timerID_;
117
119 bool timerTick_;
120
122 std::atomic<uint64_t> tickCount_;
123
125 std::atomic<uint64_t> cycleCount_;
126
128 std::atomic<uint64_t> prevTickCount_;
129
131 std::atomic<uint64_t> cycleMissedTickCount_;
132
134 int64_t start_;
135
142 MainTimer();
143
147 ~MainTimer();
148
150 MainTimer(const MainTimer&) = delete;
151
153 MainTimer& operator=(const MainTimer&) = delete;
154
155#ifdef _WIN32
167 static void CALLBACK TimerCallback(unsigned int uID, unsigned int uMsg,
168 DWORD_PTR dwUser, DWORD_PTR dw1,
169 DWORD_PTR dw2);
170#endif
171#ifdef __linux__
173 timer_t timerid_;
174
182 static void timer_handler(int sig);
183#endif
184
190 void onTimerTick();
191};
Cross-platform high-resolution periodic timer.
Definition: main_timer.h:32
uint64_t getTickCount() const
Returns the current tick count.
Definition: main_timer.cc:105
uint64_t getCycleMissedTickCount() const
Returns the number of missed timer ticks in the current cycle.
Definition: main_timer.cc:109
int64_t getElapsedTime() const
Returns the total elapsed time since the timer started.
Definition: main_timer.cc:113
static unsigned int DELAY
Static delay in milliseconds between each timer tick.
Definition: main_timer.h:37
uint64_t getCycleCount() const
Returns the number of completed wait cycles.
Definition: main_timer.cc:107
void wait()
Waits for the next timer tick to occur.
Definition: main_timer.cc:88
static std::condition_variable cv
Static condition variable used to notify waiting threads of timer ticks.
Definition: main_timer.h:43
static void notifyAllListeners()
Notifies all listeners (waiting threads) about a timer tick.
Definition: main_timer.cc:12
static MainTimer & getInstance()
Returns the singleton instance of the MainTimer.
Definition: main_timer.cc:7