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.