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 ();D ecimal 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) {Totalobj 2 = LimitObj2 + (Decimal) math.sqrt (i);}}
In addition, stopwatch has the start () and Stop () methods, and the Reset () method
Using the. NET Stopwatch class to analyze your code