Introduced:
It is convenient to loop through the code to perform the functions that need to be tested to automatically count the execution time and support multithreading.
How to use:
Performancetest p = new Performancetest (); P.setcount (10);//number of cycles (default: 1) P.setismultithread (TRUE);//Whether to start multithreaded testing (default: false) P.execute ( i = { //code that needs to be tested Response.Write (i+ "<br>"); System.Threading.Thread.Sleep (+); }, message = { //output total run time Response.Write ( message); Total execution time: 1.02206 seconds } );
Source:
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;namespace syntacticsugar{//<summary>//* Description: Program Performance test CLASS//* * Founding Date: 2015-5-30//* * Modified:-//* * Modified by: Sunkai Xuan//* Instruction: tml//</summary> public class Performancetest {private DateTime BeginTime; Private DateTime EndTime; Private Paramsmodel Params; <summary>///Set execution times (default: 1)///</summary> public void SetCount (int count) { Params.runcount = count; }///<summary>///Set Threading mode (default: false)///</summary>//<param name= "Ismul" > True for multithreading </param> public void Setismultithread (bool ismul) {params.ismultithread = Ismul; }///<summary>//constructor///</summary> public performancetest () { Params = new Paramsmodel () {runcount = 1}; }///<summary>///Execute function///</summary>//<param name= "action" ></param& Gt public void Execute (action<int> Action, action<string> rollBack) {list<thread> arr = New List<thread> (); BeginTime = DateTime.Now; for (int i = 0; i < Params.runcount; i++) {if (Params.ismultithread) { var thread = new Thread (new System.Threading.ThreadStart () = { Action (i); })); Thread. Start (); Arr. ADD (thread); } else {action (i); }} if (Params.ismultithread) {foreach (Thread T in arr) { while (t.isalive) {Thread.Sleep (10); }}} RollBack (GetResult ()); The public string GetResult () {EndTime = DateTime.Now; String totaltime = ((endtime-begintime). totalmilliseconds/1000.0). ToString ("N5"); String Reval = String. Format ("Total execution time: {0} seconds", totaltime); Console.Write (Reval); return Reval; } private class Paramsmodel {public int runcount {get; set;} public bool Ismultithread {get; set;} } }}
Performance test class, let you code to develop a good habit of testing often-asp.net C #