Project

General

Profile

5DT Data Glove plugin  1.0
dTimer.cpp
1 
6 // LICENCE
7 
8 #include "dTimer.h"
9 
11 {
12  Reset();
13 }
14 
16 {
17 }
18 
19 void Timer::Reset()
20 {
21  // Get the constant frequency
22  QueryPerformanceFrequency(&mFrequency);
23  QueryPerformanceCounter(&mStartTime);
24  mStartTick = GetTickCount();
25 
26  mLastTime = 0;
27  zeroClock = clock();
28 }
29 
30 unsigned long Timer::GetMilliseconds()
31 {
32  LARGE_INTEGER curTime;
33 
34  // Query the timer
35  QueryPerformanceCounter(&curTime);
36  LONGLONG newTime = curTime.QuadPart - mStartTime.QuadPart;
37 
38  // scale by 1000 for milliseconds
39  unsigned long newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart);
40 
41  // detect and compensate for performance counter leaps
42  // (surprisingly common, see Microsoft KB: Q274323)
43  unsigned long check = GetTickCount() - mStartTick;
44  signed long msecOff = (signed long)(newTicks - check);
45  if (msecOff < -100 || msecOff > 100)
46  {
47  // We must keep the timer running forward :)
48  LONGLONG adjust = (std::min)(msecOff * mFrequency.QuadPart / 1000, newTime - mLastTime);
49  mStartTime.QuadPart += adjust;
50  newTime -= adjust;
51 
52  // Re-calculate milliseconds
53  newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart);
54  }
55 
56  // Record last time for adjust
57  mLastTime = newTime;
58  return newTicks;
59 }
60 
61 unsigned long Timer::GetMicroseconds()
62 {
63  LARGE_INTEGER curTime;
64  QueryPerformanceCounter(&curTime);
65  LONGLONG newTime = curTime.QuadPart - mStartTime.QuadPart;
66 
67  // get milliseconds to check against GetTickCount
68  unsigned long newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart);
69 
70  // detect and compensate for performance counter leaps
71  // (surprisingly common, see Microsoft KB: Q274323)
72  unsigned long check = GetTickCount() - mStartTick;
73  signed long msecOff = (signed long)(newTicks - check);
74  if (msecOff < -100 || msecOff > 100)
75  {
76  // We must keep the timer running forward :)
77  LONGLONG adjust = (std::min)(msecOff * mFrequency.QuadPart / 1000, newTime - mLastTime);
78  mStartTime.QuadPart += adjust;
79  newTime -= adjust;
80  }
81 
82  // Record last time for adjust
83  mLastTime = newTime;
84 
85  // scale by 1000000 for microseconds
86  unsigned long newMicro = (unsigned long) (1000000 * newTime / mFrequency.QuadPart);
87  return newMicro;
88 }
89 
91 {
92  clock_t newClock = clock();
93  return (unsigned long)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000.0)) ;
94 }
95 
97 {
98  clock_t newClock = clock();
99  return (unsigned long)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000000.0)) ;
100 }