The Performance Testing class enables you to write code to develop good habits of frequent tests and write performance tests.
Introduction:
It is convenient for the function to be tested to be executed cyclically in the code to automatically calculate the execution time and support multithreading.
Usage:
PerformanceTest p = new PerformanceTest (); p. setCount (10); // number of cycles (default: 1) p. setIsMultithread (true); // whether to start the multi-thread test (default: false) p. execute (I => {// code to be tested Response. write (I + "<br>"); System. threading. thread. sleep (1000) ;}, message =>{// output the total running time Response. write (message); // total execution time: 1.02206 seconds });
Source code:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; namespace SyntacticSugar {// <summary> /// ** Description: Program Performance Test class // ** Creation Time: // ** modification time: -// ** modifier: sunkaixuan // ** usage: tml // </summary> public class PerformanceTest {private DateTime BeginTime; private DateTime EndTime; private ParamsModel Params; // <summary> // set the number of executions (default: 1) /// </summary> public void SetCount (int count) {Params. runCount = count;} // <summary> // sets the thread mode (default: false) /// </summary> /// <param name = "isMul"> true: multithreading </param> public void SetIsMultithread (bool isMul) {Params. isMultithread = isMul;} // <summary> // constructor // </summary> public PerformanceTest () {Params = new ParamsModel () {RunCount = 1 };} /// <summary> /// Execute the function // </summary> /// <param name = "action"> </param> 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 ();} 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 ;}}}}