Yagami Light
Yagami Light

Reputation: 139

.NET Thread.Sleep makes an offset to StopWatch counter?

I wrote this simple console code, but I cannot explain the result.

public static void Execute2()
    {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        while (sw.ElapsedMilliseconds  < 1000)
        {
            Console.WriteLine(sw.ElapsedMilliseconds);
            System.Threading.Thread.Sleep(100);
        }
    }

OUTPUT on console:

0  
127  
228  
328  
429  
530  
630  
731  
831  
931  
Press a key to continue... (no debug) 

As you can see there are about 27 ms offset after the first call, but on following calls this offset is unchanged.

I thought the 27 ms where made by the overhead of calling Thread.Sleep(), but it happens only the first time. This behaviour repeats every build (I run build without debug)

my machine is: core 2 duo @ 2.8Ghz, 2gb ram, windows xp sp3, VS2010 pro

So the question is: what is responsible of the 27ms?

Upvotes: 0

Views: 966

Answers (2)

Tomtom
Tomtom

Reputation: 9384

Call

Thread.Sleep(100);

befor starting. And do any console-output befor your "real" code

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

It can be a number of things, e.g.:

  1. The JIT warming up
  2. Initialization of the console

Upvotes: 2

Related Questions