C # use Stopwatch to check program run time

Source: Internet
Author: User
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);}  }
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.