Counters

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

Counting events is a very useful programming technique for the testing/debugging/monitoring applications. It is widely used in CCore. The class Counters is designed to simplify this task.


template <class Enum,Enum Lim,class CountType=unsigned>
class Counters : public PrintOptAdapter<Enum>
 {
   CountType counter[Lim];
   
  public:
  
   Counters();
   
   void reset();
   
   void count(Enum e) { counter[e]++; }
   
   void count(Enum e,CountType cnt) { counter[e]+=cnt; }
   
   unsigned operator [] (Enum e) const { return counter[e]; }
   
   void diff(Counters<Enum,Lim> &next);
    
   void operator += (const Counters<Enum,Lim> &obj); 

   void operator -= (const Counters<Enum,Lim> &base); 
   
   // print object
 
   template <class P>
   void print(P &out) const;
    
   template <class P,class Opt>
   void print(P &out,const Opt &opt) const;
 };

Counters is a set of counters, indexed by members of some enum:


enum Enum
 {
  E1,
  E2,
  E3,

  Lim
 };

using EnumCounters = Counters<Enum,Lim> ;

The default constructor and the method reset() set all counters to zero.

The method count() increments or increments by some value the counter with the given index.

The overloaded operator [] reads the specific counter.

The overloaded operator += adds counters from another counter set.

The overloaded operator -= subtracts counters from another counter set.

You can use the method diff() to differentiate a sequence of counters:


Counters<Enum,Lim> cur;
Counters<Enum,Lim> next;

cur.diff(next);

 //
 // temp = cur ;
 // cur = next ;
 // next = next - temp ;
 //

Finally, you can print the counters, to give names to indexes define GetTextDesc(Enum). You may specify print options per enum. Only non-null counters are printed.


E1 = 5
E2 = 1
E3 = 15