Skip to content

Instantly share code, notes, and snippets.

@tebjan
Created September 20, 2018 15:18
Show Gist options
  • Save tebjan/9e2754c79de29011b1b8f773677bd96a to your computer and use it in GitHub Desktop.
Save tebjan/9e2754c79de29011b1b8f773677bd96a to your computer and use it in GitHub Desktop.
.NET high precision busy wait timer
while (running && Mode == TimerMode.Periodic)
{
var t = stopwatch.Elapsed;
var remainingTime = FInterval - (t - FOldTime);
if (remainingTime.Ticks > 2)
{
//if there is more time left than the wait accuracy
if (remainingTime.Ticks > FWaitAccuracy.Ticks)
{
Thread.Sleep(1);
continue;
}
else //busy wait last time < wait accuracy
{
while (remainingTime.Ticks > 2)
{
//Thread.SpinWait(1)?
t = stopwatch.Elapsed;
remainingTime = FInterval - (t - FOldTime);
}
}
}
//if wait timer done, we arrive here
var interval = t - FOldTime;
LastIntervalDiff = interval - LastInterval;
LastInterval = interval;
FOldTime = t;
//do the actual work
if (FResetCounter)
{
FFramCounter = 0;
FResetCounter = false;
}
FFrameClock.Time = t.TotalSeconds;
FFrameClock.TimeDifference = interval.TotalSeconds;
FFrameClock.FrameCounter = FFramCounter++;
FSubject.OnNext(FFrameClock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment