C# Stopwatch实现计算代码运行时间

  public class CheckPointCodeTime

  {

  Stopwatch _sw = Stopwatch.StartNew();

  Queue _times = new Queue();

  double _sum = 0;

  int _maxAvgCount = 0;

  ///

  /// 当前耗时时,单位秒

  ///

  public double Time { get; set; }

  ///

  /// 平均耗时时,单位秒

  ///

  public double Average { get; set; }

  ///

  /// 构造方法

  ///

  /// 计算平均总共个数

  public CheckPointCodeTime(int maxAvgCount = 60)

  {

  _maxAvgCount = maxAvgCount;

  }

  ///

  /// 检查点

  ///

  /// 是否打印

  /// 打印的标签

  public void Check(bool isPrint = true, string printLable = "")

  {

  if (!_sw.IsRunning)

  {

  _sw.Restart();

  return;

  }

  _sw.Stop();

  Time = _sw.ElapsedMilliseconds / 1000.0;

  _times.Enqueue(Time);

  _sum += Time;

  Average = _sum / _times.Count;

  Console.WriteLine(printLable + "当前耗时(s):" + Time + " 平均耗时(s):" + Average);

  if (_times.Count >= _maxAvgCount)

  {

  _sum -= _times.Dequeue();

  }

  _sw.Restart();

  }

  }