Q: How do I evaluate the time difference between two events?
A: Accurate time difference between events cannot be evaluated by clocking the time using 'CTime::GetCurrentTime()' or by using a timer. First method is limited in its accuracy to around a second and second method has limitations of lower priority.
Here I present a function which returns the time elapsed from the last call. First call will always return a zero value. This uses the high-resolution performance counter. If it does not exist, each call will return zero.
Time difference is returned in seconds and the accuracy is determined by the high-resolution performance counter frequency.Code:float TimeDiff() { // Last counter reading static LARGE_INTEGER OldCounter = {0, 0}; LARGE_INTEGER Counter, Frequency; if (QueryPerformanceFrequency(&Frequency)) { // Gets current counter reading QueryPerformanceCounter(&Counter); // Calculates time difference (zero if called first time) float TimeDiff = OldCounter.LowPart ? (float) (Counter.LowPart - OldCounterLowPart) / Frequency.LowPart : 0; // Resets last counter reading OldCounter = Counter; // Returns time difference return TimeDiff; } else { // No high resolution performance counter; returns zero return 0; } }




Reply With Quote