How to calculate the code running performance and the code running performance

Source: Internet
Author: User

How to calculate the code running performance and the code running performance

During the development process, a function may have multiple implementation methods. To pursue code performance, we often need to compare the running time of each implementation method, so as to select the best performance implementation method. So how can we calculate the running time of a piece of code (or function)? This is what we will summarize in this article. We will summarize the following points.

Calculate the code execution time in C # code

In the C # program, we usually use the Stopwatch class to calculate the execution time of code segments (or methods). I compared the performance difference between using ++ = and using StringBuilder to concatenate strings, the sample code is as follows.

1 namespace ConsoleApplication5 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 // initialize performance counter 8 CodeTimer. initialize (); 9 10 // definition execution times 11 int iteration = 100*1000; // 0.1 million times 12 13 string s = string. empty; 14 CodeTimer. time ("String Concat", iteration, () => 15 {16 s + = "a"; 17}); 18 19 StringBuilder sb = new StringBuilder (); 20 CodeTimer. time ("StringBuilder", iteration, () => 21 {22 sb. append ("a"); 23}); 24 25 Console. readKey (); 26} 27} 28}

The running result is as follows.

I used a encapsulated performance timer here. The source code will be included later in the article.

Calculate the code execution time in SQL Server

The GetDate and DateDiff functions are generally used in SQL server to calculate the running time of SQL statements. The sample code is as follows.

1 USE PackageFHDB; 2 GO 3 4 -- start time 5 DECLARE @ t1 as datetime; 6 SELECT @ t1 = GETDATE (); 7 8 -- run SQL statement 9 SELECT TOP 1000 * FROM dbo. pkg_PkgOrderMaster; 10 11 -- PRINT the result 12 print datediff (millisecond, @ t1, GETDATE ());

The execution result is 293 ms, for example.

Appendix: source code of the performance Timer

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. diagnostics; 6 using System. threading; 7 using LNFramework. common. extends; 8 using System. runtime. interopServices; 9 10 namespace LNFramework. common. tools11 {12 // <summary> 13 // performance timer 14 /// </summary> 15 public static class CodeTimer16 {17 /// <summary> 18 /// initialize 19 /// </summary> 20 public static void Initialize () 21 {22 // set the priority of the current process and thread to the highest level to reduce the interference caused by the scheduling of the operating system. 23 // call the Time method for preheating, so that the Time method enters the status 24 Process as soon as possible. getCurrentProcess (). priorityClass = ProcessPriorityClass. high; 25 Thread. currentThread. priority = ThreadPriority. highest; 26 Time ("", 1, () => {}); 27} 28 29 // <summary> 30 // timing 31 // </summary> 32 // <param name = "name"> name </param> 33 // <param name = "iteration"> Number of cycles </param> 34 // <param name = "action"> method body </param> 35 public static void time (string name, int iteration, Action action) 36 {37 if (name. isNullOrEmpty () return; 38 39 // 1. retain the foreground color of the current Console, and use the yellow output name parameter 40 lelecolor currentForeColor = Console. foregroundColor; 41 Console. foregroundColor = ConsoleColor. yellow; 42 Console. writeLine (name); 43 44 // 2. force GC to collect and record the number of times each generation has collected 45 GC. collect (GC. maxGeneration, GCCollectionMode. forced); 46 int [] gcCounts = new int [GC. maxGeneration + 1]; 47 for (int I = 0; I <= GC. maxGeneration; I ++) 48 {49 gcCounts [I] = GC. collectionCount (I); 50} 51 52 // 3. run the code to record the time consumed and CPU clock cycle 53 Stopwatch watch = new Stopwatch (); 54 watch. start (); 55 ulong cycleCount = GetCycleCount (); 56 for (int I = 0; I <iteration; I ++) 57 {58 action (); 59} 60 ulong cpuCycles = GetCycleCount ()-cycleCount; 61 watch. stop (); 62 63 // 4. restore the default foreground color of the Console, and print out the consumption time and CPU clock cycle 64 Console. foregroundColor = currentForeColor; 65 Console. writeLine ("\ tTime Elapsed: \ t" + watch. elapsedMilliseconds. toString ("N0") + "ms"); 66 Console. writeLine ("\ tCPU Cycles: \ t" + cpuCycles. toString ("N0"); 67 68 // 5. print the number of garbage collection times for each generation during execution 69 for (int I = 0; I <= GC. maxGeneration; I ++) 70 {71 int count = GC. collectionCount (I)-gcCounts [I]; 72 Console. writeLine ("\ tGen" + I + ": \ t" + count); 73} 74 75 Console. writeLine (); 76} 77 78 private static ulong GetCycleCount () 79 {80 ulong cycleCount = 0; 81 QueryThreadCycleTime (GetCurrentThread (), ref cycleCount); 82 return cycleCount; 83} 84 85 [DllImport ("kernel32.dll")] 86 [return: financialas (UnmanagedType. bool)] 87 static extern bool QueryThreadCycleTime (IntPtr threadHandle, ref ulong cycleTime); 88 89 [DllImport ("kernel32.dll")] 90 static extern IntPtr GetCurrentThread (); 91} 92}View Code

References:

A simple performance counter: CodeTimer

Related Article

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.