Jan 19, 2011

.NET System.Diagnostics.Stopwatch may be wrong

The .NET System.Diagnostics.Stopwatch timer is a software based timer and it will not count while device is in sleep mode as CPU is not running. Only less accurate real time clock will keep running.

Found this when timing a long web service call. Suppose this is the case for operations not using full CPU ticks.

Example code:

Console.WriteLine("start...");
var sw = System.Diagnostics.Stopwatch.StartNew();
System.Threading.Thread.Sleep(5000);
sw.Stop();
Console.WriteLine(string.Format("Elaped: {0} ({1} ms)", sw.Elapsed, sw.ElapsedMilliseconds));


May results in something like:

start...
Elaped: 00:00:02.3029859 (2302 ms)

No comments:

Post a Comment