/*
* HiResTimer.h
* Jonathan Boldiga
* 09/30/03
*
* Description: Wrapper for the high-resolution timer. Can't be used if the hi-res timer
* doesn't exist.
*
*/
#ifndef __TIMER_H_INCLUDED__
#define __TIMER_H_INCLUDED__
#include
class HiResTimer{
public:
HiResTimer(){}
~HiResTimer(){}
/*
* If the hi-res timer is present, the tick rate is stored and the function
* returns true. Otherwise, the function returns false, and the timer should
* not be used.
*/
bool init(){
if (!QueryPerformanceFrequency(&ticksPerSecond)){
// system doesn't support hi-res timer
return false;
}
else{
QueryPerformanceCounter(&startTime);
return true;
}
}
//Get the time elapsed in seconds
float getElapsedSeconds(unsigned long elapsedFrames = 1){
static LARGE_INTEGER lastTime = startTime;
LARGE_INTEGER currentTime;
QueryPerformanceCounter(¤tTime);
float seconds = ((float)currentTime.QuadPart - (float)lastTime.QuadPart) / (float)ticksPerSecond.QuadPart;
//reset the timer
lastTime = currentTime;
return seconds;
}
/*
* Returns the average frames per second over elapsedFrames, which defaults to
* one. If this is not called every frame, the client should track the number
* of frames itself, and reset the value after this is called.
*/
float getFPS(unsigned long elapsedFrames = 1){
static LARGE_INTEGER lastTime = startTime;
LARGE_INTEGER currentTime;
QueryPerformanceCounter(¤tTime);
float fps = (float)elapsedFrames * (float)ticksPerSecond.QuadPart / ((float)currentTime.QuadPart - (float)lastTime.QuadPart);
// reset the timer
lastTime = currentTime;
return fps;
}
/*
* Used to lock the frame rate to a set amount. This will block until enough
* time has passed to ensure that the fps won't go over the requested amount.
* Note that this can only keep the fps from going above the specified level;
* it can still drop below it. It is assumed that if used, this function will
* be called every frame. The value returned is the instantaneous fps, which
* will be <= targetFPS.
*/
float lockFPS(unsigned char targetFPS){
if (targetFPS == 0)
targetFPS = 1;
static LARGE_INTEGER lastTime = startTime;
LARGE_INTEGER currentTime;
float fps;
// delay to maintain a constant frame rate
do{
QueryPerformanceCounter(¤tTime);
fps = (float)ticksPerSecond.QuadPart/((float)(currentTime.QuadPart - lastTime.QuadPart));
} while (fps > (float)targetFPS);
// reset the timer
lastTime = startTime;
return fps;
}
private:
LARGE_INTEGER startTime;
LARGE_INTEGER ticksPerSecond;
};
#endif