If you are concerned that some code is very time consuming, you can use stopwatch to check how long this code consumes, as shown in the following code
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch (); timer. Start ();D ecimal total = 0;int limit = 1000000;for (int i = 0, i < limit; ++i) {Total = total + (Decimal) math.sqrt (i );} Timer. Stop (); Console.WriteLine ("Sum of Sqrts: {0}", total); Console.WriteLine ("Elapsed milliseconds: {0}", timer. Elapsedmilliseconds); Console.WriteLine ("Elapsed time: {0}", timer. Elapsed);
There are now specialized tools to detect the running time of the program, which can be refined to each method, such as the Dotnetperformance software.
In the above code example, you need to modify the source code directly, if it is used to test the program, it is not convenient. Please refer to the example below.
Class AutoStopwatch:System.Diagnostics.Stopwatch, idisposable{public autostopwatch () { Start (); } public void Dispose () { Stop (); Console.WriteLine ("Elapsed: {0}", this. Elapsed);} }
With the using syntax, as shown in the following code, you can check the run time of a piece of code and print it on the console.
using (new Autostopwatch ()) { Decimal total2 = 0; int limit2 = 1000000; for (int i = 0; i < limit2; ++i) { Total2 = Total2 + (Decimal) math.sqrt (i);} }