Use Stopwatch to Measure Code Execution Time

February 28th 2006 .NET Framework

One of the most common tasks when analyzing performance and optimizing code is measuring the time it takes to execute the code in question. Before .NET 2.0 you had to develop your own high resolution timer for the job by wrapping the unmanaged calls to QueryPerformanceCounter and QueryPerformanceFrequency.

I kept using the same class in .NET 2.0 but just the other day I stumbled across the Stopwatch class in the System.Diagnostics namespace. It implements the same high resolution timer functionality out of the box, so there's no need to use unmanaged calls to achieve it anymore.

And the basic usage couldn't be simpler:

using System.Diagnostics;  
// ...  
Stopwatch sw = new Stopwatch();  
// do some processing here  
Debug.WriteLine("Time elapsed:" + sw.ElapsedMilliseconds.ToString());

One wonders what other hidden treasures lie in the class library yet to be discovered.

Creative Commons License