00001 /* -*- mode: c++ -*- */ 00002 #ifndef __DAQpp_GTimer_included__ 00003 #define __DAQpp_GTimer_included__ 00004 00005 #include <unistd.h> 00006 #include <sys/time.h> 00007 00008 namespace DAQpp 00009 { 00018 class GTimer 00019 { 00020 private: 00022 struct timeval _start; 00024 struct timeval _end; 00026 bool active; 00027 00028 public: 00030 GTimer(); 00032 ~GTimer() 00033 {} 00035 void start(); 00037 void stop(); 00039 void reset(); 00041 double operator()() const; 00043 bool is_active() const 00044 { 00045 return active; 00046 } 00047 }; 00048 } 00049 00050 inline DAQpp::GTimer::GTimer() 00051 { 00052 start(); 00053 } 00054 inline void DAQpp::GTimer::start() 00055 { 00056 active = true; 00057 gettimeofday (&_start, NULL); 00058 } 00059 inline void DAQpp::GTimer::stop() 00060 { 00061 active = false; 00062 gettimeofday (&_end, NULL); 00063 } 00064 inline void DAQpp::GTimer::reset() 00065 { 00066 gettimeofday (&_start, NULL); 00067 _end = _start; 00068 } 00069 inline double DAQpp::GTimer::operator()() const 00070 { 00071 double total; 00072 struct timeval elapsed; 00073 struct timeval end; 00074 00075 if ( active ) gettimeofday (&end, NULL); 00076 else end = _end; 00077 if (_start.tv_usec > end.tv_usec) 00078 { 00079 end.tv_usec += 1000000; 00080 end.tv_sec--; 00081 } 00082 elapsed.tv_usec = end.tv_usec - _start.tv_usec; 00083 elapsed.tv_sec = end.tv_sec - _start.tv_sec; 00084 00085 total = elapsed.tv_sec + ((double) elapsed.tv_usec) / 1.e6; 00086 return total; 00087 } 00088 #endif