/// <summary>
/// 秒表计时器
/// </summary>
public class StopWatch
{
/// <summary>
/// 一个步骤
/// </summary>
class StepClass
{
public string stepname;
public DateTime start;
public DateTime end;
}
private string _name;
private DateTime _start;
private DateTime _stepstart;
private double _skipMS;
private List<StepClass> _steps;
public StopWatch() : this("未命名") { }
public StopWatch(string name)
{
_name = name;
_start = DateTime.Now;
_stepstart = _start;
_steps = new List<StepClass>();
_skipMS = 0;
}
/// <summary>
/// 记一个步骤
/// </summary>
/// <param name="name"></param>
public void Step(string name)
{
_steps.Add(new StepClass()
{
stepname = name,
start = _stepstart,
end = DateTime.Now
});
_stepstart = DateTime.Now;
}
/// <summary>
/// 跳过这段时间
/// </summary>
/// <param name="skipTotalTime"></param>
public void Skip(bool skipTotalTime = false)
{
if (skipTotalTime) _skipMS += DateTime.Now.Subtract(_stepstart).TotalMilliseconds;
_stepstart = DateTime.Now;
}
/// <summary>
/// 到现在为止的用时
/// </summary>
public double TotalMS
{
get { return DateTime.Now.Subtract(_start).TotalMilliseconds - _skipMS; }
}
/// <summary>
/// 计时信息
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"计时器:{_name},总用时= {TotalMS:0.0} 毫秒,开始时间={_start:HH:mm:ss.fff},步骤数={_steps.Count}");
for(int i= 0; i<_steps.Count;i++)
{
sb.AppendLine($" {i:00} 用时= {_steps[i].end.Subtract(_steps[i].start).TotalMilliseconds,6:0.0} 毫秒\t{_steps[i].stepname}\t开始时间={_steps[i].start:HH:mm:ss.fff}");
}
return sb.ToString();
}
/// <summary>
/// 记录到日志
/// </summary>
public void ToLog()
{
Log.info($"{ToString()}");
}
}