Timer.h 1.28 KB
Newer Older
Francois Gygi committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
////////////////////////////////////////////////////////////////////////////////
//
//  Timer.h
//
////////////////////////////////////////////////////////////////////////////////
// $Id: Timer.h,v 1.1.1.1 2002-09-27 00:08:39 fgygi Exp $

#ifndef TIMER_H
#define TIMER_H

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

class Timer
{
  private:

  clock_t clk;
  double t,total_cpu,total_real;
  int running_;

  public:

  Timer() : total_cpu(0.0), total_real(0.0), running_(0) {};

  void reset() { total_cpu = 0.0; total_real = 0.0; running_ = 0; };

  void start()
  {
    clk = clock();
    t = gtod();
    running_ = 1;
  };

  int running() { return running_; };

  void stop()
  {
    if ( running_ ) 
    {
      total_cpu += ((double)(clock()-clk))/CLOCKS_PER_SEC;
      total_real += gtod()-t;
      running_ = 0;
    }
  };

  double cpu()
  {
    if ( running_ ) 
    {
      return total_cpu + ((double)(clock()-clk))/CLOCKS_PER_SEC;
    }
    else
    {
      return total_cpu;
    } 
  };

  double real()
  {
    if ( running_ ) 
    {
      return total_real + gtod()-t;
    }
    else
    {
      return total_real;
    } 
  };

  double gtod(void)
  {
    static struct timeval tv;
    static struct timezone tz;
    gettimeofday(&tv,&tz);
    return tv.tv_sec + 1.e-6*tv.tv_usec;
  }
};
#endif