Using the .NET Stopwatch class to Profile Your Code

It is important for any developer to know what is the load time of a page. For this purpose you can use the System.Diagnostics.Stopwatch class to determine the time elapsed to open the page. 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);
Output: 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 using {} syntax to dispose the object:
        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.

PS: If you want to check the timeline for every page. Add this code on the top and bottom of your Masterpage, and HTML comment the output of the Stopwatch results at the bottom of the page.