Skip to content

Instantly share code, notes, and snippets.

@saga
Created April 15, 2011 15:28
Show Gist options
  • Save saga/921881 to your computer and use it in GitHub Desktop.
Save saga/921881 to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.InteropServices;
class HighResolutionTimer
{
private bool isPerfCounterSupported = false;
private Int64 frequency = 0;
// Windows CE native library with QueryPerformanceCounter().
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int QueryPerformanceCounter(ref Int64 count);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int QueryPerformanceFrequency(ref Int64 frequency);
public HighResolutionTimer()
{
int returnVal = QueryPerformanceFrequency(ref frequency);
if (returnVal != 0 && frequency != 1000)
{
// The performance counter is supported.
isPerfCounterSupported = true;
}
else
{
// The performance counter is not supported. Use
// Environment.TickCount instead.
frequency = 1000;
}
Start();
}
public Int64 Frequency
{
get
{
return frequency;
}
}
public Int64 Value
{
get
{
Int64 tickCount = 0;
if (isPerfCounterSupported)
{
// Get the value here if the counter is supported.
QueryPerformanceCounter(ref tickCount);
return tickCount;
}
else
{
// Otherwise, use Environment.TickCount.
return (Int64)Environment.TickCount;
}
}
}
private Int64 _startValue;
public void Start()
{
_startValue = Value;
}
public Int64 Stop()
{
Int64 stopValue = Value;
return stopValue - _startValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment