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 </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