PerfTimer.h
Code: Select all
#ifndef _PERFTIMER_H
#define _PERFTIMER_H
#include <windows.h>
#include <string>
#include <mmsystem.h>
#include <ctime>
using namespace std;
#define STRING_SIZE 255
class PerfTimer
{
protected:
double m_TimeScale;
double m_Time;
double m_DeltaTime;
unsigned int m_FrameCount;
double m_ElapsedTime ;
TCHAR *m_Buffer;
wstring m_Output;
public:
PerfTimer();
~PerfTimer();
double GetTime();
void SetTime();
double DeltaTime(PerfTimer & P1);
void OutputFrameRate(HWND & windowHandle);
};
Code: Select all
#include "PerfTimer.h"
PerfTimer::PerfTimer()
{
__int64 countsPerSecond = 0;
if(QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSecond) != 0)
{
m_TimeScale = 1.0 / (double)countsPerSecond;
}
else
{
m_TimeScale = 0.0;
m_Time = 0.0; // set to zero if no performance timer available
}
m_FrameCount = 0;
m_ElapsedTime = 0.0;
m_Buffer = new TCHAR[STRING_SIZE];
}
PerfTimer::~PerfTimer() {
delete[] m_Buffer;
}
double PerfTimer::GetTime()
{
return m_Time;
}
void PerfTimer::SetTime()
{
__int64 currentTime = 0;
QueryPerformanceCounter((LARGE_INTEGER*)¤tTime);
m_Time = currentTime * m_TimeScale;
}
double PerfTimer::DeltaTime(PerfTimer & P1)
{
m_DeltaTime = GetTime() - P1.GetTime();
return m_DeltaTime;
}
void PerfTimer::OutputFrameRate(HWND & windowHandle)
{
// increment the frame count
m_FrameCount++;
// calculate how much time has passed since the last frame
m_ElapsedTime += m_DeltaTime;
// if 1 second has passed
if( m_ElapsedTime >= 1.0 )
{
// calculate frames per second.
// FPS = frameCnt / timeElapsed however only computed when elapsedTime = 1.0
// Therefore FPS = frameCnt / 1.0 = frameCnt.
m_Output = L"Frames Per Second = ";
_itow_s(m_FrameCount,m_Buffer,20,10);
m_Output += m_Buffer;
// set the window caption
SetWindowText(windowHandle, m_Output.c_str());
// Reset
m_FrameCount = 0;
m_ElapsedTime = 0.0f;
}
}
Code: Select all
...
PerfTimer P1;
PerfTimer P2;
P1.SetTime();
double sleepElapsedTime = 0.0;
// Game loop!
while (1)
{
P2.SetTime(); // Get current time
sleepElapsedTime += P2.DeltaTime ( P1 ); // Get Delta time
P2.OutputFrameRate( hwnd ); // Output FPS to caption (Pass the window handle)
SwapBuffers(hDC);
while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!GetMessage (&msg, NULL, 0, 0))
{
PostQuitMessage(0);
break;
}
TranslateMessage (&msg);
DispatchMessage (&msg);
}
P1 = P2;
}