StopWatch Accuracy in .NET
02/15/2010 at 06:33 PMIt 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:
- Some may question the accuracy of Thread.Sleep, which I did at first. However, the DateTime measurement rules that out, as it's always over 100ms.
- I executed this on XP with an AMD processor and on my MBP running Windows 2003 via VMware Fusion
- DateTime is a value type, so it will perform better and faster than StopWatch
b
Pending approval by moderator
Pending approval by moderator
