Thursday, May 26, 2011

Measuring time with Stopwatches

.NET 2.0 added the Stopwatch class that should definitely be in your tool belt for performance testing.
From MSDN:

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.
Stopwatch stopWatch = Stopwatch.StartNew();
// Code to benchmark
Console.WriteLine ("{0} ms", stopWatch.Elapsed.TotalMilliseconds);

Also note that the ElapsedMilliseconds property returns a rounded number to the nearest full millisecond, the Elapsed.TotalMilliseconds property is a float that can return execution times to the partial millisecond.

Update: Eric Lippert has a new series on benchmarking and highlights this approach in his second post.

No comments: