Timer.h 1.75 KB
Newer Older
Francois Gygi committed
1 2
////////////////////////////////////////////////////////////////////////////////
//
Francois Gygi committed
3 4 5 6
// Copyright (c) 2008 The Regents of the University of California
//
// This file is part of Qbox
//
Francois Gygi committed
7 8
// Qbox is distributed under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 2 of
Francois Gygi committed
9 10 11 12 13 14
// the License, or (at your option) any later version.
// See the file COPYING in the root directory of this distribution
// or <http://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////////////
//
Francois Gygi committed
15 16 17
//  Timer.h
//
////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
18
// $Id: Timer.h,v 1.4 2008-09-08 15:56:19 fgygi Exp $
Francois Gygi committed
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

#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()
  {
51
    if ( running_ )
Francois Gygi committed
52 53 54 55 56 57 58 59 60
    {
      total_cpu += ((double)(clock()-clk))/CLOCKS_PER_SEC;
      total_real += gtod()-t;
      running_ = 0;
    }
  };

  double cpu()
  {
61
    if ( running_ )
Francois Gygi committed
62 63 64 65 66 67
    {
      return total_cpu + ((double)(clock()-clk))/CLOCKS_PER_SEC;
    }
    else
    {
      return total_cpu;
68
    }
Francois Gygi committed
69 70 71 72
  };

  double real()
  {
73
    if ( running_ )
Francois Gygi committed
74 75 76 77 78 79
    {
      return total_real + gtod()-t;
    }
    else
    {
      return total_real;
80
    }
Francois Gygi committed
81 82 83 84 85 86 87 88 89 90 91
  };

  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