Created
September 20, 2018 15:18
-
-
Save tebjan/9e2754c79de29011b1b8f773677bd96a to your computer and use it in GitHub Desktop.
.NET high precision busy wait timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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