Blue Blip

Thoughts Technologies Ramblings Learning & Sharing

Profiling .NET Code with StopWatch

One of the new diagnostics tools introduced in .NET 2.0 is the System.Diagnostics.StopWatch class. It lets you time your code with simplest profiling code possible! And I use this class very regularly during my development/desting. I use it especially when calling out to external APIs such as web services, remoting, etc. Here is an example:
using System;
using System.Diagnostics;
... ...
StopWatch sw = new StopWatch();
sw.Start();
// Code calling web service, database, etc.
sw.Stop();
Console.WriteLine ("Elapsed time (in ms): " + sw.ElapsedMilliseconds);

As a side note, StopWatch is a friendly wrapper .NET class for the QueryPerformanceCounter Win32 API. StopWatch.Start() invokes this API and stores the tick value and StopWatch.Stop() does it again and the difference in the ticks is exposed as the elapsed duration. what this means is that you can use the Win32 API directly in .NET 1.x applications to profile your code.

Posted: Oct 09 2006, 05:15 PM by Siva M | with no comments
Filed under: ,