March 26, 2008

.NET Code Performance Measurement

When improving the performance of your code, it's often usefull to know how fast (or slow) your code is running. I was going to show you a neat little class that I've been using for years that wraps some Win32 API functions, but my pre-blogging research has revealed that my approach is a bit outdated. Since .NET 2.0 there has been just such a wrapper class baked into the framework. It's the System.Diagnostics.Stopwatch class. It's use is simple:


Stopwatch timer = new Stopwatch();
timer.Start();

...Code to evaluate goes here...

timer.Stop();
double elapsed = timer.ElapsedMilliseconds;

In addition to getting the ElapsedMilliseconds, you can also access the Elapsed property to get a timespan or ElapsedTicks to get the ticks.