
Minimum Wait Time (System Time Resolution)
Thanks all for the help. The solution I implemented is below:
All I do to use this code is as follows:
long lastTime = //The last time I did someting
long period = //some number of uSec
AccurateTimer.Wait((lastTime+period)-AccurateTimer.Now)
public class AccurateTimer
{
[DllImport("kernel32.dll")]
extern static short QueryPerformanceCounter(ref long x);
[DllImport("kernel32.dll")]
extern static short QueryPerformanceFrequency(ref long x);
[DllImport("ntdll.dll")]
extern static short NtQueryTimerResolution(ref long MinimumResolution,
ref long MaximumResolution,
ref long ActualResolution);
/// <summary>
/// Performance Counter ticks/uSec
/// </summary>
static readonly long pcPeruSec;
/// <summary>
/// System Timer resolution in uSec
/// </summary>
static readonly long sysTimerResolution;
/// <summary>
/// Sets up constants
/// </summary>
static AccurateTimer()
{
//Compute the number of perf counter ticks /uSec
long x = 0;
QueryPerformanceFrequency(ref x);
pcPeruSec=(x/1000000);
//Determines the min System Timer resolution in uSec
long a=0,b=0,c=0;
NtQueryTimerResolution(ref a, ref b, ref c);
sysTimerResolution = c/10;
}
/// <summary>
/// Waits for a min period of the specified uSec
/// </summary>
/// <param name="uSec">The number of uSec to wait</param>
public static void Wait(long uSec)
{
if (uSec<=0)
return;
//The time we entered the function
long start = 0;
QueryPerformanceCounter(ref start);
//The time when we can return
long end = start+(uSec*pcPeruSec);
//Sleep it is feasible
if(uSec>sysTimerResolution)
{
Thread.Sleep((int)(uSec/1000));
}
//Busy wait (but yield the thread) until it is time to return
long now = 0;
while(now<end)
{
Thread.Sleep(0);
QueryPerformanceCounter(ref now);
}
}
/// <summary>
/// Provides the current perf counter time in uSec
/// </summary>
public static long Now
{
get
{
long x = 0;
QueryPerformanceCounter(ref x);
return x/pcPeruSec;
}
}
Quote:
}
Quote:
> Why is it that the code:
> DateTime a, b;
> a=DateTime.Now;
> System.Threading.Thread.Sleep(1);
> b=DateTime.Now;
> TimeSpan c = b-a;
> Console.WriteLine(c.TotalMilliseconds);
> Always results in a wait of 15.6243 versus 1 as I would expect.
> I understand that this has something to do with the resolution of the
system
> timer. Is there anyway to change this?
> I need to do something 100 times/sec and no faster. Using Sleep(10) still
> results in a 15.6 ms wait therefore I cannot do what I need to do any
faster
> than 64 times per second.
> Any suggestions???
> DAve