代码之家  ›  专栏  ›  技术社区  ›  Sam Saffron James Allen

如何显示在页脚中生成页面所用的持续时间?

  •  6
  • Sam Saffron James Allen  · 技术社区  · 16 年前

    在调试构建期间,我想显示在服务器端生成页页脚中的页所花的时间。

    因此,例如,如果一个页面占用了250毫秒的服务器端,我希望在调试版本的页脚中显示该页面。如何在ASP.NET MVC项目中实现这一点?

    2 回复  |  直到 16 年前
        1
  •  5
  •   Marnix van Valen    16 年前

    将此添加到母版页的页脚:

    Page rendering took <%= DateTime.Now.Subtract( this.ViewContext.HttpContext.Timestamp ).TotalMilliseconds.ToString() %>

    您还可以将其包装在扩展方法中:

    public static class Extensions
    {
      public static string RequestDurationinMs( this HtmlHelper helper )
      {
        #if DEBUG
        return DateTime.Now.Subtract( helper.ViewContext.HttpContext.Timestamp ).TotalMilliseconds.ToString();
        #endif
      }
    }

    像这样使用:

    <%= Html.RequestDurationinMs() %>
    

    您可能需要导入扩展类的命名空间: <%@ Import Namespace="Your.Namespace" %>

        2
  •  1
  •   Sunday Ironfoot    16 年前

    这个 ViewContext.HttpContext.Timestamp 马尼克斯建议的事情很聪明,我还没意识到那是真的。但是,您也可以将其作为一个HTTPmodule来完成,它也可以在非MVC应用程序中工作:

    using System;
    using System.Web;
    
    namespace MyLibrary
    {
        public class PerformanceMonitorModule : IHttpModule
        {
            public void Dispose() { }
    
            public void Init(HttpApplication context)
            {
                context.PreSendRequestContent += delegate(object sender, EventArgs e)
                {
                    HttpContext httpContext = ((HttpApplication)sender).Context;
                    if (httpContext.Response.ContentType == "text/html")
                    {
                        DateTime timestamp = httpContext.Timestamp;
    
                        double seconds = (double)DateTime.Now.Subtract(timestamp).Ticks / (double)TimeSpan.TicksPerSecond;
                        string result = String.Format("{0:F4} seconds ({1:F0} req/sec)", seconds, 1 / seconds);
    
                        httpContext.Response.Write("<div style=\"position: fixed; right: 5px; bottom: 5px; font-size: 15px; font-weight: bold;\">Page Execution Time: " + result + "</div>");
                    }
                };
            }
        }
    }
    

    然后将其放入web.config:

    <httpModules>
        <!-- Other httpModules (snip) -->
    
        <add name="PerformanceMonitor" type="MyLibrary.PerformanceMonitorModule, MyLibrary"/>
    </httpModules>
    

    这将记录将HTML内容发送到浏览器之前的最后时刻,以便尽可能多地测量HTTP管道。不确定在页面标记中粘贴viewContext.httpContext.timestamp是否可以实现此目的?

    注意:这不会产生有效的HTML标记,因为它会 <div> 到页面底部,因此仅用于开发/性能分析。

    编辑 :我修改了httpmodule以使用httpcontext.timestamp,而不是在请求上下文中存储秒表对象,因为它似乎提供了更准确的结果。

    推荐文章