MXS-2078 Add IntervalTimer

IntervalTimer is used for accumulating intervals (i.e. durations) over sections of code.
This commit is contained in:
Niclas Antti
2018-11-01 09:21:50 +02:00
parent 56d28d703c
commit 13a0390de6
2 changed files with 55 additions and 0 deletions

View File

@ -101,6 +101,40 @@ private:
TimePoint m_lap;
};
/** IntervalTimer for accumulating intervals (i.e. durations). Do not expect many very short
* durations to accumulate properly (unless you have a superfast processor, RTLinux, etc.)
*
* Usage pattern:
* IntervalTimer timer; // created ahead of time.
* ...
* In some sort of a loop (explicit or implicit):
* timer.start_interval();
* foo();
* timer.end_interval();
* ...
* And finally:
* std::cout << timer.total() << std::endl;
*
*/
class IntervalTimer
{
public:
/** Create but do not start the intervaltimer, i.e. starting in paused mode. */
IntervalTimer();
/** Resume measuring time. Ok to call multiple times without an end_interval(). */
void start_interval();
/** Pause measuring time. */
void end_interval();
/** Total duration of intervals (thus far). */
Duration total() const;
private:
TimePoint m_last_start;
Duration m_total;
};
/** Returns the duration as a double and string adjusted to a suffix like ms for milliseconds.
* The double and suffix (unit) combination is selected to be easy to read.
* This is for output conveniece. You can always convert a duration to a specific unit:

View File

@ -46,6 +46,27 @@ Duration StopWatch::restart()
m_start = m_lap = now;
return split;
}
IntervalTimer::IntervalTimer() : m_total(0)
{
}
void IntervalTimer::start_interval()
{
m_last_start = Clock::now();
}
void IntervalTimer::end_interval()
{
m_total += Clock::now() - m_last_start;
// reset to make it easier to spot usage bugs, like calling end_interval(); end_interval();
m_last_start = TimePoint();
}
Duration IntervalTimer::total() const
{
return m_total;
}
} // maxbase
/********** OUTPUT ***********/