13#include <dpsim-models/Logger.h>
14#include <dpsim/Config.h>
24 using Ticks = std::chrono::nanoseconds;
26 using StartClock = std::chrono::system_clock;
27 using IntervalClock = std::chrono::steady_clock;
29 using StartTimePoint = std::chrono::time_point<StartClock, Ticks>;
30 using IntervalTimePoint = std::chrono::time_point<IntervalClock, Ticks>;
33 enum State { running, stopped } mState;
35 StartTimePoint mStartAt;
36 IntervalTimePoint mNextTick;
52 enum Flags :
int { fail_on_overrun = 1 };
54 Timer(
int flags = 0, CPS::Logger::Level logLevel = CPS::Logger::Level::debug);
58 void start(
const StartTimePoint &startAt);
70 const long long &overruns() {
return mOverruns; }
72 long long ticks() {
return mTicks; }
74 Ticks interval() {
return mTickInterval; }
77 void setStartTime(
const StartTimePoint &start) { mStartAt = start; }
79 void setInterval(
const Ticks &intv) { mTickInterval = intv; }
81 void setInterval(
double dt) {
82 mTickInterval = Timer::Ticks((uintmax_t)(dt * 1e9));
87template <
class Rep,
class Period>
88struct timespec to_timespec(std::chrono::duration<Rep, Period> dur) {
89 auto nsDur = std::chrono::duration_cast<std::chrono::nanoseconds>(dur);
93 ts.tv_sec = nsDur.count() / 1000000000;
94 ts.tv_nsec = nsDur.count() % 1000000000;
106template <
typename Clock,
typename Duration>
108operator<<(std::ostream &stream,
109 const std::chrono::time_point<Clock, Duration> &time_point) {
110 const auto sys_time_point =
111 std::chrono::time_point_cast<typename Clock::duration, Clock>(time_point);
112 const std::time_t time = Clock::to_time_t(sys_time_point);
115 ((__GNUC__ == 4) && __GNUC_MINOR__ > 8 && __GNUC_REVISION__ > 1)
118 localtime_r(&time, &tm);
119 return stream << std::put_time(&tm,
"%c");
120#elif defined(_MSC_VER)
122 ctime_s(buffer, 26, &time);
124 return stream << buffer;
127 ctime_r(&time, buffer);
129 return stream << buffer;
133template <
typename Rep,
typename Period>
134std::ostream &operator<<(std::ostream &stream,
135 const std::chrono::duration<Rep, Period> &dur) {
137 using namespace std::chrono;
141 if (dur == dur.zero())
144 auto h = duration_cast<hours>(d);
146 auto m = duration_cast<minutes>(d);
148 auto s = duration_cast<seconds>(d);
150 auto ms = duration_cast<milliseconds>(d);
152 auto us = duration_cast<microseconds>(d);
154 auto ns = duration_cast<nanoseconds>(d);
156 long long vals[] = {h.count(), m.count(), s.count(),
157 ms.count(), us.count(), ns.count()};
158 const char *units[] = {
"hrs",
"mins",
"secs",
"msecs",
"usecs",
"nsecs"};
160 for (
int i = 0; i < 6; i++) {
167 stream << vals[i] <<
" " << units[i];
void start()
Start real-time timer.
void stop()
Stop real-time timer.
CPS::Logger::Log mSLog
Logger.
void sleep()
Suspend thread execution until next tick.
CPS::Logger::Level mLogLevel
Timer log level.