12 #include <dpsim-models/Definitions.h>
13 #include <dpsim/Timer.h>
16 #include <sys/timerfd.h>
20 using namespace DPsim;
23 Timer::Timer(
int flags)
24 : mState(stopped), mOverruns(0), mTicks(0), mFlags(flags) {
26 mTimerFd = timerfd_create(CLOCK_MONOTONIC, 0);
31 std::cerr <<
"WARNING: No high resolution timer available. Clock might drift!"
37 if (mState == State::running)
46 uint64_t ticks = 0, overruns;
51 bytes = read(mTimerFd, &ticks,
sizeof(ticks));
56 std::this_thread::sleep_until(mNextTick);
58 auto now = IntervalClock::now();
60 while (mNextTick < now) {
61 mNextTick += mTickInterval;
68 mOverruns += overruns;
73 if (mFlags & Flags::fail_on_overrun)
79 assert(mState == stopped);
85 auto rt = StartClock::now();
86 auto steady = IntervalClock::now();
92 auto start = mStartAt > StartTimePoint()
93 ? mStartAt.time_since_epoch() - rt.time_since_epoch() +
94 steady.time_since_epoch()
95 : steady.time_since_epoch();
99 struct itimerspec ts = {.it_interval = to_timespec(mTickInterval),
100 .it_value = to_timespec(
start)};
102 ret = timerfd_settime(mTimerFd, TFD_TIMER_ABSTIME, &ts, 0);
107 mNextTick = IntervalTimePoint(
start) + mTickInterval;
108 mState = State::running;
112 assert(mState == State::running);
116 struct itimerspec ts = {.it_interval = {0, 0}, .it_value = {0, 0}};
118 ret = timerfd_settime(mTimerFd, 0, &ts, 0);
124 mState = State::stopped;
void start()
Start real-time timer.
void stop()
Stop real-time timer.
void sleep()
Suspend thread execution until next tick.