How to display the time needed to create a page in the page footer?

During debug builds, I would like to show how long it took the server side to create the page in the page footer.

So, for example, if the page takes 250 ms on the server side, I would like it to appear in the footer, in debug builds. How can I achieve this in an ASP.NET MVC project?

+6
asp.net-mvc asp.net-mvc-2
source share
2 answers

Add this to the footer on the main page:

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

You can also wrap this with an extension method:

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

Use it as follows:

 <%= Html.RequestDurationinMs() %> 

You may need to import the namespace of the extensions class: <%@ Import Namespace="Your.Namespace" %>

+5
source share

ViewContext.HttpContext.Timestamp thing suggested by Marnix is ​​smart, I did not understand what it was. However, you can also do this as an HttpModule, which will also work in an application other than 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>"); } }; } } } 

Then put this in your web.config:

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

This will record the time at the very last moment when it will be delivered before the HTML content is sent to the browser so that it measures the HTTP pipeline as much as possible. Not sure if you can stick ViewContext.HttpContext.Timestamp in your page layout?

Note: this will not lead to valid HTML markup because it overlays a <div> on the bottom of the page, therefore it is used only for development / performance analysis.

EDIT : I modified the HttpModule to use HttpContext.Timestamp instead of storing the stopwatch object in the request context, as it seems to give more accurate results.

+1
source share

All Articles