Swarm-NG  1.1
stopwatch.h
Go to the documentation of this file.
1 /*************************************************************************
2  * Copyright (C) 2010 by Mario Juric and the Swarm-NG Development Team *
3  * *
4  * This program is free software; you can redistribute it and/or modify *
5  * it under the terms of the GNU General Public License as published by *
6  * the Free Software Foundation; either version 3 of the License. *
7  * *
8  * This program is distributed in the hope that it will be useful, *
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
11  * GNU General Public License for more details. *
12  * *
13  * You should have received a copy of the GNU General Public License *
14  * along with this program; if not, write to the *
15  * Free Software Foundation, Inc., *
16  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
17  ************************************************************************/
18 
25 #pragma once
26 
27 #include <time.h>
28 #include <sys/time.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 
33 class stopwatch
34 {
35 protected:
36  struct timeval start_time;
37  float diff_time;
38  float total_time;
39  bool running;
41 
42 public:
43  stopwatch() :
44  start_time(),
45  diff_time(0.0),
46  total_time(0.0),
47  running(false),
49  { }
50 
52  void start()
53  {
54  gettimeofday( &start_time, 0);
55  running = true;
56  }
57 
60  void stop()
61  {
62  diff_time = getDiffTime();
64  running = false;
66  }
67 
70  void reset()
71  {
72  diff_time = 0;
73  total_time = 0;
74  clock_sessions = 0;
75  if( running )
76  {
77  gettimeofday( &start_time, 0);
78  }
79  }
80 
85  float getTime() const
86  {
87  float retval = total_time;
88  if(running)
89  {
90  retval += getDiffTime();
91  }
92  return 0.001 * retval;
93  }
94 
97  void addTime(const float dt)
98  {
99  total_time += 1000*dt;
100  }
101 
104  float getAverageTime() const
105  {
106  return 0.001 * total_time/clock_sessions;
107  }
108 
109  int nSessions() const
110  {
111  return clock_sessions;
112  }
113 
114 private:
115 
117 
118  float getDiffTime() const
119  {
120  struct timeval t_time;
121  gettimeofday( &t_time, 0);
122 
123  // time difference in milli-seconds
124  return (float) (1000.0 * ( t_time.tv_sec - start_time.tv_sec)
125  + (0.001 * (t_time.tv_usec - start_time.tv_usec)) );
126  }
127 };
128 
134 template< class T >
135 double watch_time(const T& a){
136  stopwatch s;
137  s.start();
138  a();
139  SYNC;
140  s.stop();
141  return s.getTime()*1000.;
142 }
143