/* Timer.h provides a simple, platform-independent interval timer
 *  that measures CPU usage in "clocks" 
 *  -- some fraction of a second that is implementation dependent.
 *  
 *  See Timer.doc for documentation of the operations.
 *
 * Author: Joel Adams, for Hands On C++.
 * Date:   November 1997
 *
 * Revision History
 *
 * Seconds() added - kvlinden, 5-Feb-98
 *
 */

#ifndef TIMER
#define TIMER

#include <iostream.h> // ostream
#include <time.h>     // C time library: clock_t, clock(), CLOCKS_PER_SEC

class Timer
{
public:
  Timer();
  void Start();
  void Stop();
  void Reset();
  void Print(ostream & out) const;
  clock_t Time() const;
  double Seconds() const;

private:
  clock_t myStartTime;
  clock_t myRunTime;
  bool running;
};

inline Timer::Timer()
{
  myStartTime = myRunTime = 0;
  running = false;
}

inline void Timer::Start()
{
  running = true;
  myStartTime = clock();
}

inline void Timer::Stop()
{
  if (running)
    {
      myRunTime += clock() - myStartTime;
      running = false;
    }
}

inline void Timer::Reset()
{
  myRunTime = 0;
  myStartTime = clock();
}

inline void Timer::Print(ostream & out) const
{
  if (running)
    out << (clock() - myStartTime);
  else
    out << myRunTime;
}

inline ostream & operator<< (ostream & out, const Timer & aTimer)
{
  aTimer.Print(out);
  return out;
}

inline clock_t Timer::Time() const
{
  if (running)
    return (clock() - myStartTime);
  else
    return myRunTime;
}

inline double Timer::Seconds() const
{
  if (running)
    return (double)(clock() - myStartTime) / (double)CLOCKS_PER_SEC;
  else
    return (double)myRunTime / (double)CLOCKS_PER_SEC;
}

#endif

