diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs b/src/libraries/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs index 37b34bf3730195..158442337b90ef 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/tests/CounterSampleCalculatorTests.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections; -using System.Collections.Specialized; using Xunit; +using Xunit.Sdk; namespace System.Diagnostics.Tests { @@ -17,16 +16,27 @@ public static void CounterSampleCalculator_ElapsedTime() PerformanceCounter counterSample = CreateCounter(categoryName, PerformanceCounterType.ElapsedTime); - counterSample.RawValue = Stopwatch.GetTimestamp(); - DateTime Start = DateTime.Now; - Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()); - - System.Threading.Thread.Sleep(500); - - var counterVal = Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()); - var dateTimeVal = DateTime.Now.Subtract(Start).TotalSeconds; - Helpers.DeleteCategory(categoryName); - Assert.True(Math.Abs(dateTimeVal - counterVal) < .3); + try + { + // Timing comparisons can be flaky under CI load, so retry. + RetryHelper.Execute(() => + { + long startTimestamp = Stopwatch.GetTimestamp(); + counterSample.RawValue = startTimestamp; + Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()); + + System.Threading.Thread.Sleep(500); + + var counterVal = Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()); + var elapsed = (double)(Stopwatch.GetTimestamp() - startTimestamp) / Stopwatch.Frequency; + Assert.True(Math.Abs(elapsed - counterVal) < .3, $"Expected elapsed ({elapsed:F3}s) and counterVal ({counterVal:F3}s) to be within 0.3s"); + }, maxAttempts: 3, retryWhen: e => e is XunitException); + } + finally + { + counterSample.Dispose(); + Helpers.DeleteCategory(categoryName); + } } public static PerformanceCounter CreateCounter(string categoryName, PerformanceCounterType counterType)