当前位置: 移动技术网 > IT编程>开发语言>c# > C#代码性能测试类(简单实用)

C#代码性能测试类(简单实用)

2019年07月18日  | 移动技术网IT编程  | 我要评论
介绍: 可以很方便的在代码里循环执行 需要测试的函数  自动统计出执行时间,支持多线程。   使用方法: performancetest

介绍:

可以很方便的在代码里循环执行 需要测试的函数  自动统计出执行时间,支持多线程。

 

使用方法:

performancetest p = new performancetest();
p.setcount(10);//循环次数(默认:1)
p.setismultithread(true);//是否启动多线程测试 (默认:false)
p.execute(
i =>
{
  //需要测试的代码
  response.write(i+"<br>");
  system.threading.thread.sleep(1000);
 
 
},
message =>
{
 
  //输出总共运行时间
  response.write(message);  //总共执行时间:1.02206秒
 
}
);

源码:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
 
namespace syntacticsugar
{
  /// <summary>
  /// ** 描述:程序性能测试类
  /// ** 创始时间:2015-5-30
  /// ** 修改时间:-
  /// ** 修改人:sunkaixuan
  /// ** 使用说明:tml
  /// </summary>
  public class performancetest
  {
    private datetime begintime;
    private datetime endtime;
    private paramsmodel params;
 
    /// <summary>
    ///设置执行次数(默认:1)
    /// </summary>
    public void setcount(int count)
    {
      params.runcount = count;
    }
    /// <summary>
    /// 设置线程模式(默认:false)
    /// </summary>
    /// <param name="ismul">true为多线程</param>
    public void setismultithread(bool ismul)
    {
      params.ismultithread = ismul;
    }
 
    /// <summary>
    /// 构造函数
    /// </summary>
    public performancetest()
    {
      params = new paramsmodel()
      {
        runcount = 1
      };
    }
 
    /// <summary>
    /// 执行函数
    /// </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("总共执行时间:{0}秒", totaltime);
      console.write(reval);
      return reval;
    }
 
    private class paramsmodel
    {
      public int runcount { get; set; }
      public bool ismultithread { get; set; }
    }
  }
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网