Game Development Reference
In-Depth Information
Create a new class called PreciseTimer . It's not a big class, so here's the code
all in one go. Have a look through it and try to work out what it's doing.
using System.Runtime.InteropServices;
namespace GameLoop
{
public class PreciseTimer
{
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceFrequency(ref long
PerformanceFrequency);
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceCounter(ref long
PerformanceCount);
long _ticksPerSecond ¼ 0;
long _previousElapsedTime ¼ 0;
public PreciseTimer()
{
QueryPerformanceFrequency(ref _ticksPerSecond);
GetElapsedTime(); // Get rid of first rubbish result
}
public double GetElapsedTime()
{
long time ¼ 0;
QueryPerformanceCounter(ref time);
double elapsedTime ¼ (double)(time - _previousElapsedTime) /
(double)_ticksPerSecond;
_previousElapsedTime ¼ time;
return elapsedTime;
}
}
}
The QueryPerformanceFrequency function retrieves the frequency of
the high-resolution performance counter. Most modern hardware has a high-
resolution timer; this function is used to get the frequency at which the timer
increments. The QueryPerformanceCounter function retrieves the current
value of the high-resolution performance counter. These can be used together to
time how long the last frame took.
 
Search WWH ::




Custom Search