Use more a reliable time source in Windows for the Timer class

This commit is contained in:
vsonnier 2017-05-20 13:20:29 +02:00
parent a541e55ff6
commit c1fef72103
2 changed files with 18 additions and 3 deletions

View File

@ -5,13 +5,18 @@
#ifdef _WIN32
#include <windows.h>
#include <mmsystem.h>
#endif
#include <iostream>
Timer::Timer(void) : time_elapsed(0), system_milliseconds(0), start_time(0), end_time(0), last_update(0), num_updates(0), paused_time(0), offset(0), paused_state(false), lock_state(false), lock_rate(0)
{
#ifdef _WIN32
// According to Microsoft, QueryPerformanceXXX API is perfectly
//fine for Windows 7+ systems, and use the highest appropriate counter.
//this only need to be done once.
::QueryPerformanceFrequency(&win_frequency);
#endif;
}
@ -82,7 +87,12 @@ void Timer::update(void)
{
#ifdef _WIN32
system_milliseconds = timeGetTime ();
//Use QuaryPerformanceCounter, imune to problems sometimes
//multimedia timers have.
LARGE_INTEGER win_current_count;
::QueryPerformanceCounter(&win_current_count);
system_milliseconds = (unsigned long)(win_current_count.QuadPart * 1000.0 / win_frequency.QuadPart);
#else
gettimeofday(&time_val,&time_zone);

View File

@ -18,6 +18,7 @@
class Timer {
private:
//units are microsecs:
unsigned long time_elapsed;
unsigned long system_milliseconds;
unsigned long start_time;
@ -30,7 +31,9 @@ private:
#ifndef _WIN32
struct timeval time_val;
struct timezone time_zone;
#endif
#else
LARGE_INTEGER win_frequency;
#endif;
bool paused_state;
bool lock_state;
@ -91,6 +94,7 @@ public:
* \return Total time elapsed since the timer start() to the last update() excluding time paused() in milliseconds
*/
unsigned long getMilliseconds(void);
/// Alias of getMilliseconds() which returns time in seconds
/**
* \return Total time elapsed since the timer start() to the last update() excluding time paused() in seconds
@ -159,6 +163,7 @@ public:
*/
bool paused();
void timerTestFunc();
};