SoFunction
Updated on 2025-03-07

C# code performance test class (simple and practical)

introduce:

It can be easily executed in the code. Functions that need to be tested automatically count the execution time and support multi-threading.

 

How to use:

PerformanceTest p = new PerformanceTest();
(10);//The number of loops (default: 1)(true);//Whether to start multi-threaded test (default: false)(
i =>
{
  //Code that needs to be tested  (i+"<br>");
  (1000);
 
 
},
message =>
{
 
  //Output total running time  (message);  //Total execution time: 1.02206 seconds 
}
);

Source code:

using System;
using ;
using ;
using ;
using ;
 
namespace SyntacticSugar
{
  /// <summary>
  /// ** Description: Program performance test class  /// ** Founding date: 2015-5-30  /// ** Modification time:-  /// ** Modified by: sunkaixuan  /// ** Instructions for use: 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)
    {
       = count;
    }
    /// <summary>
    /// Set thread mode (default: false)    /// </summary>
    /// <param name="isMul">true is multi-threaded</param>    public void SetIsMultithread(bool isMul)
    {
       = isMul;
    }
 
    /// &lt;summary&gt;
    /// Constructor    /// &lt;/summary&gt;
    public PerformanceTest()
    {
      Params = new ParamsModel()
      {
        RunCount = 1
      };
    }
 
    /// &lt;summary&gt;
    /// Execute function    /// &lt;/summary&gt;
    /// &lt;param name="action"&gt;&lt;/param&gt;
    public void Execute(Action&lt;int&gt; action, Action&lt;string&gt; rollBack)
    {
      List&lt;Thread&gt; arr = new List&lt;Thread&gt;();
      BeginTime = ;
      for (int i = 0; i &lt; ; i++)
      {
        if ()
        {
          var thread = new Thread(new (() =&gt;
          {
            action(i);
          }));
          ();
          (thread);
        }
        else
        {
          action(i);
        }
      }
      if ()
      {
        foreach (Thread t in arr)
        {
          while ()
          {
            (10);
          }
        }
 
      }
      rollBack(GetResult());
    }
 
    public string GetResult()
    {
      EndTime = ;
      string totalTime = ((EndTime - BeginTime).TotalMilliseconds / 1000.0).ToString("n5");
      string reval = ("Total execution time:{0}Second", totalTime);
      (reval);
      return reval;
    }
 
    private class ParamsModel
    {
      public int RunCount { get; set; }
      public bool IsMultithread { get; set; }
    }
  }
}