Skip to content

Commit

Permalink
fix: <1ms performance measurement support
Browse files Browse the repository at this point in the history
Signed-off-by: Maximilien Noal <noal.maximilien@gmail.com>
  • Loading branch information
maximilien-noal committed Nov 9, 2024
1 parent 41229b1 commit d8c2155
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/Spice86.Shared/Diagnostics/PerformanceMeasurer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,37 @@ public class PerformanceMeasurer : IPerformanceMeasurer {
/// <inheritdoc />
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;
ValuePerMillisecond = valueDelta / Math.Max(millisecondsDelta, 1);
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);
Expand Down

0 comments on commit d8c2155

Please sign in to comment.