When we debug, optimize our code, want to know the actual execution time of a piece of code, or we suspect that a piece of code, or a few pieces of code execution is relatively slow,
Need to get specific execution time for a particular piece of code. There is a very useful class stopwatch.
The Stopwatch class is under the System.Diagnostics namespace. Basic tools that you can use to analyze. NET code blocks.
For example:
System.Diagnostics.Stopwatch timerobj = new System.Diagnostics.Stopwatch ();
Timerobj.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 Result:
Sum of Square roots:666666166.45882210823608
Milliseconds elapsed:282
Time elapsed:00:00:00.2828692
When you use stopwatch to debug your time, you can use the IDisposable interface to automatically switch off stopwatch
1. Define a custom Stopwatch class that inherits System.Diagnostics.Stopwatch and IDisposable
Class AutoStopwatchDemo:System.Diagnostics.Stopwatch, IDisposable
{
Public Autostopwatchdemo ()
{
Start ();
}
public void Dispose ()
{
Stop ();
Console.WriteLine ("Elapsed: {0}", this. Elapsed);
}
}
2. Use in the code block you want to debug
using (new Autostopwatchdemo ())
{
Decimal totalObj2 = 0;
int limitObj2 = 1000000;
for (int i = 0; i < limit2; ++i)
{
TotalObj2 = LimitObj2 + (Decimal) math.sqrt (i);
}
}
In addition, stopwatch has the Reset () method In addition to the start () and Stop () methods,