MEL
Microthread & Execution library
Timer.h
1 #pragma once
2 #include <MelLibType.h>
3 #include <stdint.h>
4 #ifdef WIN32
5 #elif defined( MEL_IOS ) || defined( MEL_MACOSX )
6 #include <mach/mach_time.h>
7 #elif defined( MEL_LINUX ) || defined( MEL_ANDROID )
8 #include <time.h>
9 #endif
10 
11 #include <cassert>
12 struct tm; // predeclaration
13 namespace mel
14 {
15  namespace core
16  {
17  class MEL_API Timer
18  {
19 
20  public:
25  Timer();
26  virtual ~Timer();
27 
32  virtual void reset();
36  void pause();
37  void resume();
42  inline uint64_t getMilliseconds() const;
46  inline uint64_t getLastMilliseconds() const;
47  inline bool getPaused() const;
51  inline uint64_t getStartTime() const;
52  inline void setStartTime( uint64_t );
53 
54  protected:
55  uint64_t mReference; // reference time when Timer is created, units
56  // depends on platform
57  uint64_t mStartTime;
58 #ifdef WIN32
59  uint64_t mFrequency;
60  mutable uint64_t mLastTime;
61 #elif defined( MEL_IOS ) || defined( MEL_MACOSX )
62  mach_timebase_info_data_t mTimeBase;
63  mutable uint64_t mLastTime;
64 #elif defined( MEL_LINUX ) || defined( MEL_ANDROID )
65  mutable uint64_t mLastTime;
66 #endif
67  uint64_t mMsActive;
68  private:
69  enum
70  {
71  ACTIVE,
72  PAUSED
73  } mState;
74  };
75  uint64_t Timer::getMilliseconds() const
76  {
77  uint64_t result;
78  if ( mState == ACTIVE )
79  {
80 #ifdef WIN32
81  uint64_t tmp;
82  QueryPerformanceCounter( (LARGE_INTEGER*)&tmp );
83  result = ( tmp - mReference ) * 1000 /
84  mFrequency; // because counter/frecuency = seconds
85 #elif defined( MEL_IOS ) || defined( MEL_MACOSX )
86  uint64_t tmp = mach_absolute_time();
87  uint64_t elapsed = tmp - mReference;
88  result = ( elapsed * mTimeBase.numer ) / mTimeBase.denom;
89 #elif defined( MEL_LINUX ) || defined( MEL_ANDROID )
90  timespec ts;
91  uint64_t tmp;
92  int chk( clock_gettime( CLOCK_MONOTONIC, &ts ) );
93 #pragma unused( chk )
94  assert( !chk );
95  tmp = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
96  result = tmp - mReference;
97 #endif
98  }
99  else
100  {
101  // it's paused
102  result = 0;
103  }
104  mLastTime = result + mMsActive + mStartTime;
105  return mLastTime;
106  }
107  uint64_t Timer::getLastMilliseconds() const
108  {
109  //@todo no me gusta nada esta conversion y tal vez alg�n d�a
110  // tengamos problemas, pero devolver 64bits es muy ineficiente
111  // ahrora
112  return (unsigned long)mLastTime;
113  }
114  bool Timer::getPaused() const { return mState == PAUSED; }
115  uint64_t Timer::getStartTime() const { return mStartTime; }
116  void Timer::setStartTime( uint64_t v ) { mStartTime = v; }
117  } // namespace core
118 } // namespace mel
Definition: Timer.h:18
virtual void reset()
uint64_t getLastMilliseconds() const
Definition: Timer.h:107
uint64_t getMilliseconds() const
Definition: Timer.h:75
uint64_t getStartTime() const
Definition: Timer.h:115
Definition: Callback_Impl.h:11