stopwatch.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #ifndef __STOPWATCH_TIMER_H__
  2. #define __STOPWATCH_TIMER_H__
  3. #include <sys/time.h>
  4. class stopwatch_unit_t {
  5. public:
  6. class sec {
  7. public:
  8. static inline unsigned int gettime(void) {
  9. return time(NULL);
  10. };
  11. };
  12. class msec {
  13. public:
  14. static inline unsigned int gettime(void) {
  15. struct timeval tv;
  16. gettimeofday(&tv, NULL);
  17. return tv.tv_sec * 1000 + tv.tv_usec/1000;
  18. };
  19. };
  20. class usec {
  21. public:
  22. static inline unsigned int gettime(void) {
  23. struct timeval tv;
  24. gettimeofday(&tv, NULL);
  25. return tv.tv_sec * 1000000 + tv.tv_usec;
  26. };
  27. };
  28. };
  29. template<typename T>
  30. class stopwatch_t {
  31. private:
  32. unsigned int _value;
  33. public:
  34. inline stopwatch_t(void) { _value = 0; }
  35. inline stopwatch_t(bool started) { _value = started ? T::gettime() : 0; }
  36. inline stopwatch_t(unsigned int v) { _value = v; }
  37. inline stopwatch_t(const stopwatch_t &v) { _value = v._value; }
  38. inline ~stopwatch_t(void) {}
  39. /* start timer now */
  40. inline void start(void) { _value = T::gettime(); }
  41. /* start from timestamp:v */
  42. inline void init(unsigned int v) { _value = v; }
  43. inline stopwatch_t & operator =(unsigned int v) { _value = v; return *this; }
  44. /* stop watch */
  45. inline void stop(void) { _value = T::gettime() - _value; }
  46. /* get counter _value */
  47. inline unsigned int get(void) { return _value; }
  48. inline operator unsigned int(void) const { return _value; }
  49. inline unsigned int live(void) const { return T::gettime() - _value; }
  50. };
  51. typedef stopwatch_t<stopwatch_unit_t::sec> stopwatch_sec_t;
  52. typedef stopwatch_t<stopwatch_unit_t::msec> stopwatch_msec_t;
  53. typedef stopwatch_t<stopwatch_unit_t::usec> stopwatch_usec_t;
  54. #endif