|
|
@@ -52,33 +52,27 @@ namespace YSAI.Unility
|
|
|
/// <summary>
|
|
|
/// 开关
|
|
|
/// </summary>
|
|
|
- private Stopwatch stopwatch;
|
|
|
+ private ValueStopwatch stopwatch;
|
|
|
|
|
|
/// <summary>
|
|
|
/// 开始记录
|
|
|
/// </summary>
|
|
|
public void StartRecord()
|
|
|
{
|
|
|
- if (stopwatch == null)
|
|
|
- {
|
|
|
- stopwatch = new Stopwatch();
|
|
|
- }
|
|
|
- stopwatch.Start(); // 开始监视代码运行时间
|
|
|
+ stopwatch = ValueStopwatch.StartNew(); // 开始监视代码运行时间
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 停止记录
|
|
|
/// </summary>
|
|
|
- /// <returns>时,分,秒,毫秒</returns>
|
|
|
+ /// <returns>时,分,秒,毫秒,时分秒毫秒</returns>
|
|
|
public (int hours, int minutes, int seconds, int milliseconds) StopRecord()
|
|
|
{
|
|
|
- stopwatch.Stop(); // 停止监视
|
|
|
- TimeSpan timespan = stopwatch.Elapsed; // 获取当前实例测量得出的总时间
|
|
|
- int hours = timespan.Hours; // 总小时
|
|
|
- int minutes = timespan.Minutes; // 总分钟
|
|
|
- int seconds = timespan.Seconds; // 总秒数
|
|
|
- int milliseconds = timespan.Milliseconds; // 总毫秒数
|
|
|
- stopwatch.Restart();//复位
|
|
|
+ TimeSpan timespan = stopwatch.GetElapsedTime(); // 获取当前实例测量得出的总时间
|
|
|
+ int hours = Math.Round(timespan.TotalHours).ToInt(); // 总小时
|
|
|
+ int minutes = Math.Round(timespan.TotalMinutes).ToInt(); // 总分钟
|
|
|
+ int seconds = Math.Round(timespan.TotalSeconds).ToInt(); // 总秒数
|
|
|
+ int milliseconds = Math.Ceiling(timespan.TotalMilliseconds).ToInt(); // 总毫秒数
|
|
|
return (hours, minutes, seconds, milliseconds);
|
|
|
}
|
|
|
|
|
|
@@ -94,5 +88,39 @@ namespace YSAI.Unility
|
|
|
while (stopTime.Elapsed.TotalMilliseconds < time) { }
|
|
|
stopTime.Stop();
|
|
|
}
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 直接操作底层,性能消耗更小
|
|
|
+ /// </summary>
|
|
|
+ internal struct ValueStopwatch
|
|
|
+ {
|
|
|
+ private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
|
|
|
+
|
|
|
+ private readonly long _startTimestamp;
|
|
|
+
|
|
|
+ public bool IsActive => _startTimestamp != 0;
|
|
|
+
|
|
|
+ private ValueStopwatch(long startTimestamp)
|
|
|
+ {
|
|
|
+ _startTimestamp = startTimestamp;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static ValueStopwatch StartNew() => new ValueStopwatch(Stopwatch.GetTimestamp());
|
|
|
+
|
|
|
+ public TimeSpan GetElapsedTime()
|
|
|
+ {
|
|
|
+ // Start timestamp can't be zero in an initialized ValueStopwatch. It would have to be literally the first thing executed when the machine boots to be 0.
|
|
|
+ // So it being 0 is a clear indication of default(ValueStopwatch)
|
|
|
+ if (!IsActive)
|
|
|
+ {
|
|
|
+ throw new InvalidOperationException("An uninitialized, or 'default', ValueStopwatch cannot be used to get elapsed time.");
|
|
|
+ }
|
|
|
+
|
|
|
+ var end = Stopwatch.GetTimestamp();
|
|
|
+ var timestampDelta = end - _startTimestamp;
|
|
|
+ var ticks = (long)(TimestampToTicks * timestampDelta);
|
|
|
+ return new TimeSpan(ticks);
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
}
|