Using the .NET Stopwatch class to Profile Your Code

The Stopwatch class in the System.Diagnostics namespace can be used a as a basic tool to profile blocks of .NET code.

System.Diagnostics.Stopwatch timerObj = new System.Diagnostics.Stopwatch();
timer.Start();
Decimal totalDec = 0;
int limit = 1000000;
for (int i = 0; i < limit; ++i)
{
totalDec = totalDec + (Decimal)Math.Sqrt(i);
}
timerObj.Stop();
Console.WriteLine(“Sum of square roots: {0}”,totalDec);
Console.WriteLine(“Milliseconds elapsed : {0}”,
timerObj.ElapsedMilliseconds);
Console.WriteLine(“Time elapsed : {0}”, timerObj.Elapsed);

This outputs the below:
Sum of square roots : 666666166.45882210823608
Milliseconds elapsed: 282
Time elapsed : 00:00:00.2828692

When using the Stopwatch for debugging you can to utilize the IDisposable interface to automate the stopwatch:

class AutoStopwatchDemo : System.Diagnostics.Stopwatch, IDisposable
{
public AutoStopwatchDemo()
{
Start();
}
public void Dispose()
{
Stop();
Console.WriteLine(“Elapsed : {0}”, this.Elapsed);
}
}

Now, you can use {} syntax:

using (new AutoStopwatchDemo())
{
Decimal totalObj2 = 0;
int limitObj2 = 1000000;
for (int i = 0; i < limit2; ++i)
{
totalObj2 = limitObj2  + (Decimal)Math.Sqrt(i);
}
}

Besides the Stopwatches Start() and Stop() methods, there is also Reset(), which stops the timer and then sets Elapsed to 0. In addition there is also the Restart() method, which sets Elapsed to 0 but the timer continues to run.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email
Uncategorized

No comments yet... Be the first to leave a reply!