Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

50%
+0 −0
Code Reviews Time measurement in an ASP.NET Core application

My team introduces lots of time measurements for various code sections that might take longer than expected in a real-life flow. These rely on initializing a StopWatch, getting the elapsed time an...

0 answers  ·  posted 8mo ago by Alexei‭

#1: Initial revision by user avatar Alexei‭ · 2024-03-12T20:40:17Z (8 months ago)
Time measurement in an ASP.NET Core application
My team introduces lots of time measurements for various code sections that might take longer than expected in a real-life flow. 

These rely on initializing a `StopWatch`, getting the elapsed time and sometimes ensuring that measurement is done even if an exception is raised.

The following tries to make this as simple as possible.

## The factory

```c#
/// <summary>
/// allows to measure time in a disposable scope
/// </summary>
public interface IStopwatchHelperFactory
{
    IStopwatchHelper Create();
    IStopwatchHelper Create(Action<TimeSpan>? measurementAction);
}

public class StopwatchHelperFactory : IStopwatchHelperFactory
{
    public IStopwatchHelper Create()
    {
        return new StopwatchHelper();
    }

    /// <summary>
    /// creates a new instance of <see cref="IStopwatchHelper"/> and specifies what happens when the measurement scope is disposed
    /// </summary>
    /// <param name="measurementAction"></param>
    /// <returns></returns>
    public IStopwatchHelper Create(Action<TimeSpan>? measurementAction)
    {
        return new StopwatchHelper(measurementAction);
    }
}
```

## The measurement helper

```c#
public interface IStopwatchHelper : IDisposable
{
    void SetMeasurementAction(Action<TimeSpan>? value);
}

public sealed class StopwatchHelper : IStopwatchHelper
{
    private readonly Stopwatch _stopwatch;
    private Action<TimeSpan>? _measurementAction;

    public StopwatchHelper()
    {
        _stopwatch = Stopwatch.StartNew();
    }

    public StopwatchHelper(Action<TimeSpan>? measurementAction) : this()
    {
        _measurementAction = measurementAction;
    }

    public void SetMeasurementAction(Action<TimeSpan>? value)
    {
        _measurementAction = value;
    }

    public void Dispose()
    {
        _measurementAction?.Invoke(Elapsed);
    }

    public TimeSpan Elapsed => _stopwatch.Elapsed;
}
```

## Setup

```c#
services.AddSingleton<IStopwatchHelperFactory, StopwatchHelperFactory>();
```

## Usage example

The following shows how to measure time spent in a function from one point until the function returns (or exception is thrown + return).

```c#

    // this is constructor injected
    private readonly IStopwatchHelperFactory _stopwatchHelperFactory;

    public async Task DoStuff()
    {
        // init code

        // start measuring time
using var sw = _stopwatchHelperFactory.Create(elapsed => _specificLoggingData.Foo.Duration = (int)elapsed.TotalMilliseconds);

        // other code might come here
    }
```

## The review

I am interested in potential issues with this solution, and possible edge cases I am missing. Coding comments, style, and bad practices are also welcomed.