Skip to content

Commit

Permalink
high precision Timer
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasByr committed Jun 20, 2023
1 parent 466255b commit 3259e0d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
6 changes: 3 additions & 3 deletions inc/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,16 +138,16 @@ class Timer {
bool is_running(void);

///@brief start the timer with a given duration in seconds
void start_timer(unsigned sec);
void start_timer(unsigned sec = 0, unsigned ms = 0, unsigned us = 0);
///@brief check for intermidiate step
///(i.e. if the timer has passed a given duration)
bool step_passed(unsigned sec);
bool step_passed(unsigned sec = 0, unsigned ms = 0, unsigned us = 0);
///@brief check for timer expiration
bool is_expired(void);
///@brief reset the timer
void reset_timer(void);
///@brief add a given duration to the timer
void add_time(unsigned sec=0, unsigned ms=0, unsigned us=0);
void add_time(unsigned sec = 0, unsigned ms = 0, unsigned us = 0);
};

} // namespace sys_pause
Expand Down
9 changes: 6 additions & 3 deletions src/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,20 @@ Timer::Timer() : running(false) {}

bool Timer::is_running() { return running; }

void Timer::start_timer(unsigned sec) {
void Timer::start_timer(unsigned sec, unsigned ms, unsigned us) {
if (running) { fmt::panic("timer already running"); }
start = std::chrono::high_resolution_clock::now();
end = start + std::chrono::seconds(sec);
end += std::chrono::milliseconds(ms);
end += std::chrono::microseconds(us);
running = true;
}

bool Timer::step_passed(unsigned sec) {
bool Timer::step_passed(unsigned sec, unsigned ms, unsigned us) {
if (!running) { return false; }
auto now = std::chrono::high_resolution_clock::now();
return now >= start + std::chrono::seconds(sec);
return now >= start + std::chrono::seconds(sec) +
std::chrono::milliseconds(ms) + std::chrono::microseconds(us);
}

bool Timer::is_expired() {
Expand Down

0 comments on commit 3259e0d

Please sign in to comment.