/* Copyright (c) 1997-2006
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
*/

#ifndef _POLYMAKE_STOPWATCH_H
#define _POLYMAKE_STOPWATCH_H

#include <sys/time.h>
#include <sys/resource.h>
#include <iostream>

namespace pm {

template <bool real_timer>
class Stopwatch {
public:
   void start() { }
   void restart() { }
   void stop() { }
   operator double() const { return 0.; }

   template <typename Traits> friend
   std::basic_ostream<char, Traits>&
   operator<< (std::basic_ostream<char, Traits>& os, const Stopwatch&) { return os; }
};

template <>
class Stopwatch<true> {
protected:
   struct rusage started;
   mutable struct rusage current;
   bool am_running;
   double elapsed;
   static double overhead;

   double diff() const {
      return double(current.ru_utime.tv_sec-started.ru_utime.tv_sec)+
	     double(current.ru_utime.tv_usec-started.ru_utime.tv_usec)/1.0e6
	     -overhead;
   }

   static void calibrate();
public:
   Stopwatch()
      : am_running(false), elapsed(0.) {
      if (overhead<0) calibrate();
   }

   void start() {
      elapsed=0.;
      restart();
   }

   void restart() {
      if (am_running) return;
      am_running=true;
      getrusage(RUSAGE_SELF,&started);
   }

   void stop() {
      if (!am_running) return;
      getrusage(RUSAGE_SELF,&current);
      elapsed+=diff();
      am_running=false;
   }

   operator double() const {
      if (!am_running) return elapsed;
      getrusage(RUSAGE_SELF,&current);
      return elapsed+diff();
   }

   template <typename Traits> friend
   std::basic_ostream<char, Traits>&
   operator<< (std::basic_ostream<char, Traits>& os, const Stopwatch<true>& w)
   {
      return os << double(w);
   }
};

} // end namespace pm

namespace polymake {
#ifdef POLY_TIMING
   typedef pm::Stopwatch<true> stopwatch;
#else
   typedef pm::Stopwatch<false> stopwatch;
#endif
}

#endif // _POLYMAKE_STOPWATCH_H

// Local Variables:
// mode:C++
// End:
