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

Changes UseEmfMiddleware to avoid allocating a new stopwatch instance per request #60

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 5 additions & 4 deletions src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public static void UseEmfMiddleware(this IApplicationBuilder app, Func<HttpConte
{
app.Use(async (context, next) =>
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var valueStopwatch = ValueStopwatch.StartNew();

await next.Invoke();
var config = context.RequestServices.GetRequiredService<EMF.Config.IConfiguration>();
var logger = context.RequestServices.GetRequiredService<IMetricsLogger>();
Expand All @@ -73,8 +73,9 @@ public static void UseEmfMiddleware(this IApplicationBuilder app, Func<HttpConte
}

await action(context, logger);
stopWatch.Stop();
logger.PutMetric("Time", stopWatch.ElapsedMilliseconds, Model.Unit.MILLISECONDS);

var elapsedTime = valueStopwatch.GetElapsedTime();
logger.PutMetric("Time", elapsedTime.TotalMilliseconds, Model.Unit.MILLISECONDS);
});
}
}
Expand Down
38 changes: 38 additions & 0 deletions src/Amazon.CloudWatch.EMF.Web/ValueStopwatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Diagnostics;

namespace Amazon.CloudWatch.EMF.Web
{
internal readonly 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);
}
}
}