C# Stopwatch shows incorrect time

Alexander Demuro picture Alexander Demuro · Aug 20, 2010 · Viewed 7.1k times · Source

I have seen other user posts which show Stopwatch measuring time spent in "Thread.Sleep(5000)" to be around 5000ms.

But my program produces the following results

for (int i = 0; i < 20; ++i)
{
    Stopwatch sw = Stopwatch.StartNew();
    DateTime start = DateTime.Now;
    Thread.Sleep(5000);
    sw.Stop();
    Console.Out.WriteLine(
        "StopWatch Diff:" + 
        sw.ElapsedMilliseconds.ToString()); 
    Console.Out.WriteLine(
        "DateTime Diff:" + 
        DateTime.Now.Subtract(start).TotalMilliseconds.ToString());
}

StopWatch Diff:1684
DateTime Diff:5262.592
StopWatch Diff:1625
DateTime Diff:4997.12
StopWatch Diff:1604
DateTime Diff:4997.12
StopWatch Diff:1601
DateTime Diff:4997.12
StopWatch Diff:1690
DateTime Diff:4997.12
StopWatch Diff:1603

Is it just me who is observing this behaviour? Why stopwatch measures 1.6 seconds when 5 seconds have actually passed. It is the time that the thread is actually running?

Answer

Mark Byers picture Mark Byers · Aug 20, 2010

The Stopwatch class is not reliable.

This is unreliable on processors that do not have a constant clock speed (most processors can reduce the clock speed to conserve energy). This is explained in detail here.