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!
After, some more debugging (inspired by Eric Lippert’s comment), I realized that my above code was doing exactly as requested. The problem was with the calling code at a higher level of abstraction feeding it extremely long wait times.
Thanks for the suggestions to use
System.Windows.Threading.DispatcherTimerandSystem.Timers.Timer(I gave both an up-vote); however, after testing each of these, they are limited to ~10 milliseconds of accuracy, which is just not quite good enough for my purposes. But, I did find that my “tight” loop code above is accurate to ~1 microsecond, which is more than enough for my current needs.An additional resource that others might find helpful is this CodeProject article about increasing the
Stopwatchaccuracy. The main idea is to essentially reduce the likelihood that your program will endure a context switch, and thus travel through the scheduling queues wasting time.