Measuring performance of ASP.NET MVC 3

房东的猫 提交于 2019-12-02 23:45:19
Lukáš Novotný

This might not be the reason why it shows that long execution time, but that attribute won't work correctly with mvc 3 when you have multiple requests at once.

In previous versions of ASP.NET MVC, action filters are create per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3, filters are cached more aggressively. Therefore, any custom action filters which improperly store instance state might be broken.

I'd recommend to instantiate new stopwatch in OnActionExecuting and save it to HttpContext.Current.Items - then you can retrieve it in OnActionExecuted and print out result.

George

More correct approach in addition to answer https://stackoverflow.com/a/5823555/504082 is to use OnResultExecuted override at the end of clock execution. When you return

ActionResponse.Success(arr.Select(x => func(x)).ToJson();

i.e. some lazy LINQ statement as a result of your action, it will be calculated after action is "executed" (function 'func' execution will not be count towards action execution time). I've got this nasty bug and couldn't figure out why my action "execution time" is 100 ms although web request executes 10 seconds. Modified code below.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SW
{
    public class StopwatchAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var stopwatch = new Stopwatch();
            filterContext.HttpContext.Items["Stopwatch"] = stopwatch;

            stopwatch.Start();
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var stopwatch = (Stopwatch)filterContext.HttpContext.Items["Stopwatch"];
            stopwatch.Stop();

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

            response.AddHeader("X-Runtime", stopwatch.Elapsed.TotalMilliseconds.ToString());
        }
    }
}

Why not have a look at page performance module from Rhino commons?

Looks like you are off by an order of magnitude. Are you sure you are reading the result correctly? Try using the Stopwatch.ElapsedMilliseconds property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!