diff --git a/src/Spice86.Shared/Diagnostics/PerformanceMeasurer.cs b/src/Spice86.Shared/Diagnostics/PerformanceMeasurer.cs index e8d6bad58..d21029f1a 100644 --- a/src/Spice86.Shared/Diagnostics/PerformanceMeasurer.cs +++ b/src/Spice86.Shared/Diagnostics/PerformanceMeasurer.cs @@ -31,14 +31,16 @@ public class PerformanceMeasurer : IPerformanceMeasurer { /// public void UpdateValue(long newMeasure) { long newTimeInMilliseconds = GetCurrentTime(); - if (_firstMeasureTimeInTicks == 0) { + if (IsFirstMeasurement()) { _firstMeasureTimeInTicks = newTimeInMilliseconds; - } else if((TimeSpan.FromTicks(newTimeInMilliseconds) - TimeSpan.FromTicks(_firstMeasureTimeInTicks)).TotalSeconds >= WindowSizeInSeconds) { - _firstMeasureTimeInTicks = newTimeInMilliseconds; - _sampledMetricsCount = 0; - AverageValuePerSecond = 0; + } else if (IsLastMeasurementExpired(newTimeInMilliseconds)) { + ResetMetrics(newTimeInMilliseconds); } + long millisecondsDelta = newTimeInMilliseconds - _lastTimeInMilliseconds; + if (millisecondsDelta == 0) { + return; + } _lastTimeInMilliseconds = newTimeInMilliseconds; long valueDelta = newMeasure - _measure; _measure = newMeasure; @@ -46,6 +48,20 @@ public void UpdateValue(long newMeasure) { AverageValuePerSecond = ApproxRollingAverage(AverageValuePerSecond, ValuePerSecond, _sampledMetricsCount++); } + private bool IsFirstMeasurement() { + return _firstMeasureTimeInTicks == 0; + } + + private void ResetMetrics(long newTimeInMilliseconds) { + _firstMeasureTimeInTicks = newTimeInMilliseconds; + _sampledMetricsCount = 0; + AverageValuePerSecond = 0; + } + + private bool IsLastMeasurementExpired(long newTimeInMilliseconds) { + return (TimeSpan.FromTicks(newTimeInMilliseconds) - TimeSpan.FromTicks(_firstMeasureTimeInTicks)).TotalSeconds >= WindowSizeInSeconds; + } + private static long ApproxRollingAverage(long measureAverage, long valuePerSecond, long sampledMetricsCount) { measureAverage -= measureAverage / Math.Max(sampledMetricsCount, 1); measureAverage += valuePerSecond / Math.Max(sampledMetricsCount, 1);