Listing 3: The Chronograph class


#ifndef CHRONO_H
#define CHRONO_H

#include <time.h>

class Chronograph
{
private:

   // when the Chronograph was started
   clock_t _start;

   // when the Chronograph was stopped
   // If _stopped != 0, the Chronograph
   // is stopped.
   clock_t _stopped;

   // when the last lap was read
   clock_t _lastlap;

   // the last elapsed time taken
   double _elapsed;

   /*
    diff() calculates the difference IN
    SECONDS between two clock_t values.
    */

   double diff(clock_t start, clock_t end)
   {
      return (end - start) / CLOCKS_PER_SEC;
   }

public:

   // default constructor
   Chronograph()
   {
      reset();
      start();
   }

   // destructor
   ~Chronograph()
   {
   }

   double start(void)
   {
      // current clock
      clock_t ct;

      // how long the Chronograph was stopped
      clock_t ctd;

      ct = clock();

      if(ct == 0)
         ct++;

      if(_stopped)
      {
         ctd = ct - _stopped;
         _start += ctd;
         _lastlap += ctd;

         _stopped = 0;

         return elapsed();
      }
      else
      {
         _lastlap = ct;
         _start = ct;
         _elapsed = 0.0;
         return _elapsed;
      }
   }

   double stop(void)
   {
      if(!_stopped)
      {
         _stopped = clock();
         if(_stopped == 0)
            _stopped++;
      }
      return elapsed();
   }
   double reset(void)
   {
      clock_t ct;     // current clock
      ct = clock();

      if(ct == 0)
         ct++;

      _lastlap = ct;
      _start = ct;
      _stopped = ct;
      _elapsed = 0.0;

      return _elapsed;
   }

   /*
    lap() returns the number of seconds
    since lap() was last called.
    */

   double lap(void)
   {
      clock_t ct;     // current clock
      double dl;      // lap time

      if(_stopped)
         ct = _stopped;
      else
      {
         ct = clock();

         if(ct == 0)
            ct++;
      }

      dl = diff(_lastlap, ct);

      if(!_stopped)
            _lastlap = ct;

      return dl;
   }

   double split(void)
   {
      return elapsed();
   }

   int isstopped(void)
   {
      if(_stopped)
         return 1;
      else
         return 0;
   }

   /*
    elapsed() returns the elapsed time in
    seconds that the Chronograph has been
    running.
    */

   double elapsed(void)
   {
      clock_t ct;     // current clock

      if(_stopped)
         ct = _stopped;
      else
      {
         ct = clock();

         if(ct == 0)
            ct++;
      }

      _elapsed = diff(_start, ct);
      return _elapsed;
   }

   double elapsedHMS(double &Hours,
                     double &Mins,
                     double &Secs);
};

#endif

// end of chrono.h

//End of File