/*

 BabbleMud - A MUD server

 Author:  Nick Gammon 
          http://www.gammon.com.au/ 

(C) Copyright Nick Gammon 2004. Permission to copy, use, modify, sell and
distribute this software is granted provided this copyright notice appears
in all copies. This software is provided "as is" without express or implied
warranty, and with no claim as to its suitability for any purpose.
 
*/

#include "timer.h"
#include <iomanip>
#include <sys/time.h>

/*

Useful timer class. Times whatever happens during its lifetime.

Can output to an output stream (which could be converted to a string, see
example, or a double.

Example of simple usage to output to cout:

  {
  timer t ("test");
  // do something
  }   // destructor outputs times to cout
  
Example of outputting to a string:

  ostringstream os;
  {
  timer t ("doing lots of things", &os);
  // do something
  } // destructor outputs time to os
  string s = os.str ();

Example of outputting to a double:

  double d = 0.0;
  {
  timer t ("test", NULL, &d);
  // do something
  }   // destructor outputs to d
  
  cout << "d = " << d << endl;

*/


// constructor remembers time it was constructed
timer::timer (const string & reason, ostream * os, double * total) 
  : reason_ (reason), os_ (os), total_ (total)
  {
  struct timeval t;
  gettimeofday (&t, NULL);
  start_ = (t.tv_sec * 1000000L) + t.tv_usec;
  if (os)
    *os_ << "Start     : " << setw (25) << left << reason_ << endl;
  };  // end constructor

// destructor gets current time, displays difference
timer::~timer () throw ()
  {
  struct timeval t;
  gettimeofday (&t, NULL);
  long long finish = (t.tv_sec * 1000000L) + t.tv_usec; 
  double total = (finish - start_) / 1000000.0;
  // increment total into supplied memory location, if wanted
  if (total_)
    *total_ += total;
  // display it if wanted
  if (os_)
    *os_ << "Time taken: " << setw (25) << left << reason_ << " = "
         << fixed << total << " seconds." << endl;
  };     // end destructor
