26 Oct 2010

Timing The Execution Time Of Your MVC Actions

8 Comments Uncategorized

I recently had the need to find out how much time elapsed during the execution of just my action, so I created a handy little action filter based on System.Diagnostics.Stopwatch.  This action filter adds the elapsed time to an HTTP header, appropriately named, X-Stopwatch

I choose to use a header instead of a response in the content body, so that it could be used both with non-HTML responses (binary, JSON, XML, etc) and HTML response.  I was amazed at the usefulness of this simple piece of code, because it instantly gave me insight in to the actual execution time of my action to see if my optimizations were having any effect.  It allowed me to monitor the execution time of code that I can specifically and easily control the performance of.

Here is the filter if you want to add it to your own projects.

public class StopwatchAttribute : ActionFilterAttribute
{
    private Stopwatch _stopwatch;

    public StopwatchAttribute()
    {
        _stopwatch = new Stopwatch();
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _stopwatch.Start();
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        _stopwatch.Stop();

        var httpContext = filterContext.HttpContext;
        var response = httpContext.Response;

        response.AddHeader("X-Stopwatch", _stopwatch.Elapsed.ToString());
    }
}

You can view the full C# File here on my GitHub repository.  This could obviously be modified to suit your own needs.

Tags: , ,
written by
Nick Berardi
subscribe
If you found this post valuable and would like to see more like it you can follow me.

8 Responses to “Timing The Execution Time Of Your MVC Actions”

  1. Reply Steve Smith says:

    Very cool. I posted about a similar implementation of putting timing around an arbitrary block of code using a using() statement (http://stevesmithblog.com/blog/great-uses-of-using-statement-in-c/). This looks handy for ASP.NET MVC diagnostics, definitely.

  2. Reply ullmark says:

    Hi,
    I noticed an error with measuring an action the way you describe. The action is cached and therefor it’s stopwatch instance is also cached which gives incorrect times.

    So I asked at SO and got the correct answer :) http://stackoverflow.com/questions/5821411/measuring-performance-of-asp-net-mvc-3

  3. Reply won says:

    great use of actionfilterattribute. btw, the github link returns a 404.

Leave a Reply