Timer

Files CCore/inc/Timer.h CCore/src/Timer.cpp

There are two generic timer classes and six instantiations.

Timer

The class Timer can be used to get a time. We need a class, because we have to store the start time.


template <class T,T Time()>
class Timer
 {
   T start;
   
  public:
  
   Timer() { reset(); }
   
   void reset() { start=Time(); }
   
   using ValueType = T ;
   
   T get() const { return Time()-start; }
   
   bool less(T lim) const { return get()<lim; }
   
   bool exceed(T lim) const { return get()>=lim; }
   
   void shift(T delta) { start+=delta; }
   
   static T Get() { return Time(); }
 };

This class is parameterized by the time value type and the time function. Constructor and the method reset() record the start time. Once you have done it, you can get a current time relative to the start time by the method get(). Methods less() and exceed() compare the current time with the given limit. The method shift() adjusts the start time. Static members ValueType and Get() present the class parameters.

The following example demonstrates the timed loop:


for(SecTimer timer; timer.less(10) ;) { .... } // repeat some job withing 10 seconds

DiffTimer

The next class DiffTimer returns the differentiated time, i.e. the time between calls.


template <class T,T Time()>
class DiffTimer
 {
   T prev;
   
  public:
  
   DiffTimer() { reset(); }
   
   void reset() { prev=Time(); }
   
   using ValueType = T ;
   
   T get() { return Diff(prev,Time()); }
 };

Here is an example:


SecDiffTimer timer; // point1

....

auto t1=timer.get(); // point2 , t1 is the time between point1 and point2

....

auto t2=timer.get(); // point3 , t2 is the time between point2 and point3

Timer classes

There are six timer class instantiations for different time resolutions — millisecond, second, and clock:


using MSecTimer = Timer<Sys::MSecTimeType,Sys::GetMSecTime> ;

using SecTimer = Timer<Sys::SecTimeType,Sys::GetSecTime> ;

using ClockTimer = Timer<Sys::ClockTimeType,Sys::GetClockTime> ;

using MSecDiffTimer = DiffTimer<Sys::MSecTimeType,Sys::GetMSecTime> ;

using SecDiffTimer = DiffTimer<Sys::SecTimeType,Sys::GetSecTime> ;

using ClockDiffTimer = DiffTimer<Sys::ClockTimeType,Sys::GetClockTime> ;

These instantiations are based on target provided functions. Clock time is a fastest available time resolution on the target, comparable with the CPU clock speed.