1

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
MrGraversen
  • 257
  • 3
  • 16
  • 5
    Please, copy paste your code, it'll be *way* easier for us to help you – Thomas Ayoub Feb 02 '15 at 13:48
  • 3
    ... uff ... because `Thread.Sleep(n)` is not guarenteed to be n-msecs ... –  Feb 02 '15 at 13:49
  • First there is an overhead switching Threads when you call Thread.Sleep. Second you cant be sure the Thread will return after 1ms. – BoeseB Feb 02 '15 at 13:50
  • your forgetting to account for the time needed to iterate, to call the method.... – Sayse Feb 02 '15 at 13:50
  • 1
    `Thread.Sleep(1)` will sleep for *at least* 1 ms. When it actually wakes back up depends on when the operating system gets back around to scheduling it. – Matt Burland Feb 02 '15 at 13:50

2 Answers2

9

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.

Community
  • 1
  • 1
1

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.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115