C # Calculates the run time of a piece of code

Source: Internet
Author: User

The first method takes advantage of System.DateTime.Now:static void subtest () {DateTime Befordt = System.DateTime.Now;  Time-consuming code DateTime Afterdt = System.DateTime.Now;  TimeSpan ts = afterdt.subtract (Befordt); Console.WriteLine ("DateTime total Cost {0}ms.", TS.) TotalMilliseconds);}  The second type is used with the Stopwatch class (system.diagnostics): static void Subtest () {Stopwatch SW = new Stopwatch (); Sw.   Start (); Time-consuming great code SW.  Stop (); TimeSpan TS2 = sw.  Elapsed; Console.WriteLine ("Stopwatch total cost {0}ms.", Ts2. TotalMilliseconds);} The third is implemented with the API: [System.Runtime.InteropServices.DllImport ("Kernel32.dll")]static extern bool QueryPerformanceCounter ( Ref long Count); [System.Runtime.InteropServices.DllImport ("Kernel32.dll")]static extern bool QueryPerformanceFrequency (ref long  count); static void Subtest () {Long count = 0;  Long count1 = 0;  Long freq = 0;  Double result = 0;  QueryPerformanceFrequency (ref freq);   QueryPerformanceCounter (ref count);  Time-consuming Code QueryPerformanceCounter (ref count1);  Count = Count1-count; result = (double) (count)/(double) Freq; Console.WriteLine ("QueryPerformanceCounter time: {0} seconds", result);} You can also use a delegate to encapsulate it for easy invocation:///<summary>/////</summary>//<param name= "function" > code to be executed &LT;/PA ram>//<returns> Execute this piece of code time, in milliseconds </returns> public static string Stopwatch (Action function) {S Ystem.       diagnostics.stopwatch SW = new System.Diagnostics.Stopwatch (); Sw.        Start ();        Start execution of business code function (); Sw.       Stop (); TimeSpan timespan = SW.        Elapsed;   Return (Timespan.totalmilliseconds) + "MS"; }

  

C # Calculates the run time of a piece of code

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.