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.
ActionFilter, asp.net mvc, Performance

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.
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
While you are right that it doesn’t work properly in MVC 3, saying this is an error on my part is wrong, because this attribute was created for MVC 2 and released a while before MVC 3 was released.
Here is the updated version:
https://github.com/managedfusion/managedfusion-web/blob/master/src/Web/Mvc/StopwatchAttribute.cs
Yes, that’s correct! My apologies!
Just wanted to comment so others won’t make the same mistake as me and think your code applies to MVC3 as well…
great use of actionfilterattribute. btw, the github link returns a 404.