13 #include <dpsim/Config.h>
23 using Ticks = std::chrono::nanoseconds;
25 using StartClock = std::chrono::system_clock;
26 using IntervalClock = std::chrono::steady_clock;
28 using StartTimePoint = std::chrono::time_point<StartClock, Ticks>;
29 using IntervalTimePoint = std::chrono::time_point<IntervalClock, Ticks>;
32 enum State { running, stopped } mState;
34 StartTimePoint mStartAt;
35 IntervalTimePoint mNextTick;
46 enum Flags :
int { fail_on_overrun = 1 };
52 void start(
const StartTimePoint &startAt);
64 const long long &overruns() {
return mOverruns; }
66 long long ticks() {
return mTicks; }
68 Ticks interval() {
return mTickInterval; }
71 void setStartTime(
const StartTimePoint &
start) { mStartAt =
start; }
73 void setInterval(
const Ticks &intv) { mTickInterval = intv; }
75 void setInterval(
double dt) {
76 mTickInterval = Timer::Ticks((uintmax_t)(dt * 1e9));
81 template <
class Rep,
class Period>
82 struct timespec to_timespec(std::chrono::duration<Rep, Period> dur) {
83 auto nsDur = std::chrono::duration_cast<std::chrono::nanoseconds>(dur);
87 ts.tv_sec = nsDur.count() / 1000000000;
88 ts.tv_nsec = nsDur.count() % 1000000000;
100 template <
typename Clock,
typename Duration>
102 operator<<(std::ostream &stream,
103 const std::chrono::time_point<Clock, Duration> &time_point) {
104 const auto sys_time_point =
105 std::chrono::time_point_cast<typename Clock::duration, Clock>(time_point);
106 const std::time_t time = Clock::to_time_t(sys_time_point);
108 #if __GNUC__ > 4 || \
109 ((__GNUC__ == 4) && __GNUC_MINOR__ > 8 && __GNUC_REVISION__ > 1)
112 localtime_r(&time, &tm);
113 return stream << std::put_time(&tm,
"%c");
114 #elif defined(_MSC_VER)
116 ctime_s(buffer, 26, &time);
118 return stream << buffer;
121 ctime_r(&time, buffer);
123 return stream << buffer;
127 template <
typename Rep,
typename Period>
128 std::ostream &operator<<(std::ostream &stream,
129 const std::chrono::duration<Rep, Period> &dur) {
131 using namespace std::chrono;
135 if (dur == dur.zero())
138 auto h = duration_cast<hours>(d);
140 auto m = duration_cast<minutes>(d);
142 auto s = duration_cast<seconds>(d);
144 auto ms = duration_cast<milliseconds>(d);
146 auto us = duration_cast<microseconds>(d);
148 auto ns = duration_cast<nanoseconds>(d);
150 long long vals[] = {h.count(), m.count(), s.count(),
151 ms.count(), us.count(), ns.count()};
152 const char *units[] = {
"hrs",
"mins",
"secs",
"msecs",
"usecs",
"nsecs"};
154 for (
int i = 0; i < 6; i++) {
161 stream << vals[i] <<
" " << units[i];
void start()
Start real-time timer.
void stop()
Stop real-time timer.
void sleep()
Suspend thread execution until next tick.