I have an application which must transmit packets at fixed intervals of 33ms +/- a few milliseconds.
So, I came up with a SpinTimer
class shown below:
class SpinTimer
{
public void SpinWait(double waitTimeInSeconds)
{
if (waitTimeInSeconds < 0.0)
{
throw new ArgumentOutOfRangeException("waitTimeInSeconds", "Must be >= 0.0");
}
Stopwatch timer = new Stopwatch();
double elapsed = 0.0;
timer.Start();
do
{
elapsed = (double)timer.ElapsedTicks / (double)Stopwatch.Frequency;
} while (elapsed < waitTimeInSeconds);
}
}
However, after profiling the code, I found that the System.Diagnostics.Stopwatch.GetTimestamp()
call was taking most of the execution time. Just as a note, I can't afford to have the thread sleep and context switch as this causes too much "jitter" in the output rate.
Notes about the profile run:
- Thread priority was set to
ThreadPriority.Highest
- Process priority was set to
ProcessPriorityClass.High
The original program that I wrote (in C++) accomplished the same effect using the QueryPerformanceCounter()
and QueryPerformanceFrequency()
functions. Should I be using these calls with PInvoke instead of the Stopwatch
class? Or, is there another appropriate way to do this?
Thanks!