Easy way to measure the execution time of an ASP.NET Core WebAPI action method.

Recently, I was working on an ASP.NET Core WebAPI project, and needed a way to measure execution time for a given API endpoint. I needed to benchmark the action method's time with and without caching enabled.

There are a number of libraries on the market, including the awesome BenchmarkDotNet; however, for this use case, I was looking for something simple, easy, and lightweight.

Show Me the Code...

I decided to use an custom action filter to solve this problem. Here is my solution:

public class BenchmarkAttribute : ActionFilterAttribute
{
    public override async Task OnActionExecutionAsync(
        ActionExecutingContext context, 
        ActionExecutionDelegate next)
    {
        var stopWatch = new Stopwatch();
        stopWatch.Start();

        await next();

        stopWatch.Stop();
        context.HttpContext.Response.Headers.Add(
            "x-time-elapsed", 
            stopWatch.Elapsed.ToString());
    }
}

How Does It Work?

  1. Create and start a new instance of Stopwatch from System.Diagnostics.
  2. Execute the action method.
  3. Stop the Stopwatch instance.
  4. Return the elapsed time in a custom response header.

To use it, simply apply the Benchmark attribute to any action method.

[Benchmark, HttpGet("{number}")]
public async Task<IActionResult> Get(int number)
{
    var result =
        await mediator.Send(new Command { Number = number });

    return Ok(result);
}

Here is the result:

Screen-Shot-2017-11-07-at-12.04.34-AM

Perhaps, this example complements my previous post, Real World Action Filters.

Enjoy!

Show Comments