Archive Blogs
February, 2010

<< Back to current Blogs

More Archives

2010 February ( 2 )
2009 July ( 1 )
2009 June ( 1 )
2009 May ( 2 )
2009 April ( 2 )

Avatar

StopWatch Accuracy in .NET

02/15/2010 at 06:33 PM

It appears StopWatch is not reliable for short running processes (e.g. 100ms). So, when I need to measure duration, I use good old fashioned DateTime.NowUtc - DateTime.NowUtc (If you're using DateTime.Now, change, unless you're 100% positive your code will always run on a server in Greenwich, London, or you don't observe daylight savings)

The following shows the inaccuracies I'm seeing. About 6 out of 7 calls, the results are fine, but about every 7th call yields weird results. As you can see, I'm checking the accuracy of StopWatch with DateTime.NowUtc. One last note, I've been told Elapsed is more accurate than ElapsedMilliseconds, which I also tried, but with similar results.

StopWatch measured 97 milliseconds.

DateTime.UtcNow measured 109 milliseconds

The Code (Console app. Don't forget the namespace System.Diagnostics):

DateTime dt = DateTime.UtcNow;

Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(100);
long ms = sw.ElapsedMilliseconds;
Console.WriteLine("StopWatch measured {0} milliseconds.", ms);
Console.WriteLine("DateTime.UtcNow measured {0} milliseconds", (DateTime.UtcNow - dt).Milliseconds);
Console.ReadLine();

Some interesting things to note:

b

Reply on 04/16/2010 at 05:28 AM
Pending approval by moderator
Reply on 04/16/2010 at 12:49 PM
Pending approval by moderator

Comment:

*Note: All replies subject to moderator approval. Content may be changed or completely removed by the moderator.

Name

Email

Body