MrGraversen
MrGraversen

Reputation: 277

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

Upvotes: 2

Views: 668

Answers (2)

Felice Pollano
Felice Pollano

Reputation: 33252

Since you are not in a real time OS, your program can be interrupt by something else, and using Sleep increase the chanches this will happen, even because the number of milliseconds you thread will wait it will be at least n milliseconds. Try with a plain Thread.Sleep(100) and you probably find something closer.

Upvotes: 1

user57508
user57508

Reputation:

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.

Upvotes: 10

Related Questions