Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: Adds use of ValueStopwatch instead of Stopwatch #3320

Merged
merged 7 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ internal static async Task<T> ExecuteRetryAsync(
TimeSpan backoffTime = result.BackoffTime;
if (inBackoffAlternateCallbackMethod != null && result.BackoffTime >= minBackoffForInBackoffCallback)
{
Stopwatch stopwatch = new Stopwatch();
ValueStopwatch stopwatch = new ValueStopwatch();
try
{
stopwatch.Start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Microsoft.Azure.Cosmos.Encryption
internal sealed class EncryptionDiagnosticsContext
{
private DateTime startTime;
private Stopwatch stopwatch;
private ValueStopwatch stopwatch;
private bool isDecryptionOperation;

public EncryptionDiagnosticsContext()
Expand All @@ -30,7 +30,7 @@ public EncryptionDiagnosticsContext()

public void Begin(string operation)
{
this.stopwatch = Stopwatch.StartNew();
this.stopwatch = ValueStopwatch.StartNew();
this.startTime = DateTime.UtcNow;

switch (operation)
Expand Down
2 changes: 1 addition & 1 deletion Microsoft.Azure.Cosmos/src/Batch/BatchAsyncBatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private async Task<object> DispatchHelperAsync(

try
{
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();

PartitionKeyRangeBatchExecutionResult result = await this.executor(serverRequest, trace, cancellationToken);

Expand Down
4 changes: 2 additions & 2 deletions Microsoft.Azure.Cosmos/src/Metrics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ namespace Microsoft.Azure.Cosmos

internal sealed class Metrics
{
private readonly Stopwatch stopwatch;
imanvt marked this conversation as resolved.
Show resolved Hide resolved
private readonly ValueStopwatch stopwatch;

public Metrics()
{
this.stopwatch = new Stopwatch();
this.stopwatch = new ValueStopwatch();
}

public int Count
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,9 @@ public static void OutputPercentileDistribution(this HistogramBase histogram,
/// </remarks>
public static void Record(this IRecorder recorder, Action action)
{
var start = Stopwatch.GetTimestamp();
var start = ValueStopwatch.GetTimestamp();
action();
var elapsed = Stopwatch.GetTimestamp() - start;
var elapsed = ValueStopwatch.GetTimestamp() - start;
recorder.RecordValue(elapsed);
}

Expand Down Expand Up @@ -251,12 +251,12 @@ private sealed class Timer : IDisposable
public Timer(IRecorder recorder)
{
_recorder = recorder;
_start = Stopwatch.GetTimestamp();
_start = ValueStopwatch.GetTimestamp();
}

public void Dispose()
{
var elapsed = Stopwatch.GetTimestamp() - _start;
var elapsed = ValueStopwatch.GetTimestamp() - _start;
_recorder.RecordValue(elapsed);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ internal static class OutputScalingFactor
/// <summary>
/// For use when values are recorded with <seealso cref="Stopwatch.GetTimestamp()"/> and output should be reported in microseconds.
/// </summary>
public static readonly double TimeStampToMicroseconds = Stopwatch.Frequency / (1000d * 1000d);
public static readonly double TimeStampToMicroseconds = ValueStopwatch.Frequency / (1000d * 1000d);

/// <summary>
/// For use when values are recorded with <seealso cref="Stopwatch.GetTimestamp()"/> and output should be reported in milliseconds.
/// </summary>
public static readonly double TimeStampToMilliseconds = Stopwatch.Frequency / 1000d;
public static readonly double TimeStampToMilliseconds = ValueStopwatch.Frequency / 1000d;

/// <summary>
/// For use when values are recorded with <seealso cref="Stopwatch.GetTimestamp()"/> and output should be reported in seconds.
/// </summary>
public static readonly double TimeStampToSeconds = Stopwatch.Frequency;
public static readonly double TimeStampToSeconds = ValueStopwatch.Frequency;
}
}
2 changes: 1 addition & 1 deletion Microsoft.Azure.Cosmos/src/OSS/HdrHistogram/TimeStamp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal static class TimeStamp
/// <returns>The number of system timer ticks that represent the <paramref name="seconds"/>.</returns>
public static long Seconds(long seconds)
{
return Stopwatch.Frequency * seconds;
return ValueStopwatch.Frequency * seconds;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ namespace Microsoft.Azure.Cosmos.Query.Core.Metrics
sealed class FetchExecutionRangeAccumulator
{
private readonly DateTime constructionTime;
private readonly Stopwatch stopwatch;
private readonly ValueStopwatch stopwatch;
private List<FetchExecutionRange> fetchExecutionRanges;
private DateTime startTime;
private DateTime endTime;
Expand All @@ -33,7 +33,7 @@ public FetchExecutionRangeAccumulator()
{
this.constructionTime = DateTime.UtcNow;
// This stopwatch is always running and is only used to calculate deltas that are synchronized with the construction time.
this.stopwatch = Stopwatch.StartNew();
this.stopwatch = ValueStopwatch.StartNew();
this.fetchExecutionRanges = new List<FetchExecutionRange>();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,17 @@ internal sealed class SchedulingStopwatch
/// <summary>
/// Stopwatch used to measure turnaround time.
/// </summary>
private readonly Stopwatch turnaroundTimeStopwatch;
private readonly ValueStopwatch turnaroundTimeStopwatch;

/// <summary>
/// Stopwatch used to measure response time.
/// </summary>
private readonly Stopwatch responseTimeStopwatch;
private readonly ValueStopwatch responseTimeStopwatch;

/// <summary>
/// Stopwatch used to measure runtime.
/// </summary>
private readonly Stopwatch runTimeStopwatch;
private readonly ValueStopwatch runTimeStopwatch;

/// <summary>
/// Number of times the process was preempted.
Expand All @@ -43,9 +43,9 @@ internal sealed class SchedulingStopwatch
/// </summary>
public SchedulingStopwatch()
{
this.turnaroundTimeStopwatch = new Stopwatch();
this.responseTimeStopwatch = new Stopwatch();
this.runTimeStopwatch = new Stopwatch();
this.turnaroundTimeStopwatch = new ValueStopwatch();
this.responseTimeStopwatch = new ValueStopwatch();
this.runTimeStopwatch = new ValueStopwatch();
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions Microsoft.Azure.Cosmos/src/Tracing/Trace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ internal sealed class Trace : ITrace
private static readonly IReadOnlyDictionary<string, object> EmptyDictionary = new Dictionary<string, object>();
private readonly List<ITrace> children;
private readonly Lazy<Dictionary<string, object>> data;
private readonly Stopwatch stopwatch;
private readonly ValueStopwatch stopwatch;
private readonly ISet<(string, Uri)> regionContactedInternal;

private Trace(
Expand All @@ -29,7 +29,7 @@ private Trace(
this.Name = name ?? throw new ArgumentNullException(nameof(name));
this.Id = Guid.NewGuid();
this.StartTime = DateTime.UtcNow;
this.stopwatch = Stopwatch.StartNew();
this.stopwatch = ValueStopwatch.StartNew();
this.Level = level;
this.Component = component;
this.Parent = parent;
Expand Down
2 changes: 1 addition & 1 deletion Microsoft.Azure.Cosmos/src/WebExceptionRetryPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ internal sealed class WebExceptionRetryPolicy : IRetryPolicy
private const int initialBackoffSeconds = 1;
private const int backoffMultiplier = 2;

private Stopwatch durationTimer = new Stopwatch();
private ValueStopwatch durationTimer = new ValueStopwatch();
private int attemptCount = 1;

// Don't penalise first retry with delay.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ private async Task WaitAndAssert(

// As this feature is thread based execution so wait for the results to avoid test flakiness
List<ClientTelemetryProperties> localCopyOfActualInfo = null;
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
do
{
await Task.Delay(TimeSpan.FromMilliseconds(1500)); // wait at least for 1 round of telemetry
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ public async Task InitTaskThreadSafe()
{
tasks.Add(this.ReadNotFound(container));
}
Stopwatch sw = Stopwatch.StartNew();

ValueStopwatch sw = ValueStopwatch.StartNew();
while(this.TaskStartedCount < 10 && sw.Elapsed.TotalSeconds < 2)
{
await Task.Delay(TimeSpan.FromMilliseconds(50));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public async Task VerifyPkRangeCacheRefreshOnSplitWithErrorsAsync()
Task backgroundItemOperatios = Task.Factory.StartNew(() => this.CreateAndReadItemBackgroundLoop(container, exceptions));

// Wait for the background job to start
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
while (!this.loopBackgroundOperaitons && stopwatch.Elapsed.TotalSeconds < 30)
{
await Task.Delay(TimeSpan.FromSeconds(.5));
Expand All @@ -96,7 +96,7 @@ public async Task VerifyPkRangeCacheRefreshOnSplitWithErrorsAsync()

// Cause direct call to hit a split exception and wait for the background job to hit it
causeSplitExceptionInRntbdCall = true;
stopwatch = Stopwatch.StartNew();
stopwatch = ValueStopwatch.StartNew();
while (causeSplitExceptionInRntbdCall && stopwatch.Elapsed.TotalSeconds < 10)
{
await Task.Delay(TimeSpan.FromSeconds(.5));
Expand All @@ -106,7 +106,7 @@ public async Task VerifyPkRangeCacheRefreshOnSplitWithErrorsAsync()

// Cause another direct call split exception
causeSplitExceptionInRntbdCall = true;
stopwatch = Stopwatch.StartNew();
stopwatch = ValueStopwatch.StartNew();
while (causeSplitExceptionInRntbdCall && stopwatch.Elapsed.TotalSeconds < 10)
{
await Task.Delay(TimeSpan.FromSeconds(.5));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ private async Task RunQueryAsync(Container container)
private async Task GetIteratorResponse<T>(FeedIterator<T> feedIterator)
{
MetricsAccumulator metricsAccumulator = new MetricsAccumulator();
Stopwatch totalTime = new Stopwatch();
Stopwatch getTraceTime = new Stopwatch();
ValueStopwatch totalTime = new ValueStopwatch();
ValueStopwatch getTraceTime = new ValueStopwatch();
string diagnosticDataPath = Path.GetFullPath(DiagnosticsDataFileName);
while (feedIterator.HasMoreResults)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class Performance
[Benchmark]
public void TestParse()
{
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
for (int i = 0; i < 100000; i++)
{
BackendMetricsParser.TryParse(delimitedString, out BackendMetrics backendMetrics);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ public async Task TestFailureOnOneThreadDoesNotFailAnother()
public async Task TestAsyncDeadlock()
{
AsyncCache<int, int> cache = new AsyncCache<int, int>();
Stopwatch stopwatch = new Stopwatch();
ValueStopwatch stopwatch = new ValueStopwatch();

stopwatch.Start();
await Task.Factory.StartNew(() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ public async Task TestTokenCredentialFailedToRefreshAsync()

// Token refreshes fails except for the first time, but the cached token will be served as long as it is valid.
// Wait for the background refresh to occur. It should fail but the cached token should still be valid
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
while (testTokenCredential.NumTimesInvoked != 3)
{
Assert.IsTrue(stopwatch.Elapsed.TotalSeconds < 10, "The background task did not start in 10 seconds");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ public async Task GetDatabaseAccountFromAnyLocationsMockTestAsync()
slowPrimaryRegionHelper.ShouldDelayRequest = (uri) => uri == defaultEndpoint || uri == new Uri(databaseAccount.ReadLocationsInternal.First().Endpoint);
slowPrimaryRegionHelper.ShouldFailRequest = slowPrimaryRegionHelper.ShouldDelayRequest;

Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
globalEndpointResult = await GlobalEndpointManager.GetDatabaseAccountFromAnyLocationsAsync(
defaultEndpoint: defaultEndpoint,
locations: new List<string>(){
Expand Down Expand Up @@ -548,7 +548,7 @@ void TraceHandler(string message)
DefaultTrace.TraceSource.Listeners.Add(new TestTraceListener { Callback = TraceHandler });
DefaultTrace.InitEventListener();

Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
// Wait for the trace message saying the background refresh occurred
while (!isGlobalEndpointRefreshStarted)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ public async Task ValidateAsyncCacheNonBlocking()
},
forceRefresh: (_) => true);

Stopwatch concurrentOperationStopwatch = Stopwatch.StartNew();
ValueStopwatch concurrentOperationStopwatch = ValueStopwatch.StartNew();
string concurrentUpdateTask = await asyncCache.GetAsync(
"test",
(_) => throw new Exception("should not refresh"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public async Task TimeoutFires()
const int resolution = 500;
using TimerWheelCore wheel = new TimerWheelCore(TimeSpan.FromMilliseconds(resolution), 10); // 10 buckets of 500 ms go up to 5000ms
TimerWheelTimer timer = wheel.CreateTimer(TimeSpan.FromMilliseconds(timerTimeout));
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
await timer.StartTimerAsync();
stopwatch.Stop();
}
Expand All @@ -123,7 +123,7 @@ public async Task TimeoutFires_SameTimeout()
using TimerWheelCore wheel = new TimerWheelCore(TimeSpan.FromMilliseconds(resolution), 10); // 10 buckets of 500 ms go up to 5000ms
TimerWheelTimer timer = wheel.CreateTimer(TimeSpan.FromMilliseconds(timerTimeout));
TimerWheelTimer timer2 = wheel.CreateTimer(TimeSpan.FromMilliseconds(timerTimeout));
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
await Task.WhenAll(timer.StartTimerAsync(), timer2.StartTimerAsync());
stopwatch.Stop();
}
Expand All @@ -142,7 +142,7 @@ public async Task MultipleTimeouts()
int estimatedTimeout = (i + 1) * timerTimeout;
TimerWheelTimer timer = wheel.CreateTimer(TimeSpan.FromMilliseconds(estimatedTimeout));
tasks.Add(Task.Run(async () => {
Stopwatch stopwatch = Stopwatch.StartNew();
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
await timer.StartTimerAsync();
stopwatch.Stop();
return (estimatedTimeout,stopwatch.ElapsedMilliseconds);
Expand Down