From 13a0390de623b14c59b5e7de3d8a7067e91d9b18 Mon Sep 17 00:00:00 2001 From: Niclas Antti Date: Thu, 1 Nov 2018 09:21:50 +0200 Subject: [PATCH] MXS-2078 Add IntervalTimer IntervalTimer is used for accumulating intervals (i.e. durations) over sections of code. --- maxutils/maxbase/include/maxbase/stopwatch.hh | 34 +++++++++++++++++++ maxutils/maxbase/src/stopwatch.cc | 21 ++++++++++++ 2 files changed, 55 insertions(+) diff --git a/maxutils/maxbase/include/maxbase/stopwatch.hh b/maxutils/maxbase/include/maxbase/stopwatch.hh index 331e00b4c..5c82b4a94 100644 --- a/maxutils/maxbase/include/maxbase/stopwatch.hh +++ b/maxutils/maxbase/include/maxbase/stopwatch.hh @@ -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: diff --git a/maxutils/maxbase/src/stopwatch.cc b/maxutils/maxbase/src/stopwatch.cc index 064dc28c9..e25f7c73e 100644 --- a/maxutils/maxbase/src/stopwatch.cc +++ b/maxutils/maxbase/src/stopwatch.cc @@ -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 ***********/