From f8120f23c800c3a7f66832c0c9821fc39d5b1ae5 Mon Sep 17 00:00:00 2001 From: phalvesr Date: Sun, 18 Aug 2024 12:34:20 -0300 Subject: [PATCH] feat: changes emf middleware to avoid memory allocation a memory allocation for every request --- .../ApplicationBuilderExtensions.cs | 9 +++-- .../ValueStopwatch.cs | 38 +++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 src/Amazon.CloudWatch.EMF.Web/ValueStopwatch.cs diff --git a/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs b/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs index 3e3610a..de08e25 100644 --- a/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs +++ b/src/Amazon.CloudWatch.EMF.Web/ApplicationBuilderExtensions.cs @@ -61,8 +61,8 @@ public static void UseEmfMiddleware(this IApplicationBuilder app, Func { - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); + var valueStopwatch = ValueStopwatch.StartNew(); + await next.Invoke(); var config = context.RequestServices.GetRequiredService(); var logger = context.RequestServices.GetRequiredService(); @@ -73,8 +73,9 @@ public static void UseEmfMiddleware(this IApplicationBuilder app, Func _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); + } + } +} \ No newline at end of file