Search code examples
c#stopwatch

Why Stopwatch seems to be inaccurate if checked with Thread.Sleep?


I tried implementing the .NET Stopwatch for fun, but I got some unexpected results.

I was fully expecting about 100 ms execution time from this program.

Is the Stopwatch class inaccurate or what is going on here?

Code:

namespace Timer
{
    class Program
    {
        Stopwatch s = new Stopwatch();

        static void Main(string[] args)
        {
            s.Start();
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(1);
            }
            s.Stop();

            Console.WriteLine("Elapsed Time " + s.ElapsedMilliseconds + " ms");

            Console.ReadKey();
        }
    }
}

Result is 190 ms


Solution

  • Because Thread.Sleep(n) means: at least for n msces.

    Some time ago I wrote an answer (on another topic though), which contained an external reference:

    Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more than n milliseconds. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

    According to MSDN:

    The system clock ticks at a specific rate called the clock resolution. The actual timeout might not be exactly the specified timeout, because the specified timeout will be adjusted to coincide with clock ticks.