Home > View Post

Time taken to render a page in ASP.NET

I was trawling through our web logs the other day and noted that we get hits from a surprising number of people looking for "Time taken to render page in ASP.NET". Which is odd - because there isn't any post here that covers that topic... yet.

We always like to help where we can, so here's a little tip I use in most of my ASP.NET web sites.

First you need to add a couple of methods to the Global.asax to intercept the appropriate stages of the page lifecycle.

First we need to capture the start of the request and store the time at which the request entered the Http pipeline. We'll use the Items collection on the current HttpContext (specific to this request) to store the start time.

void Application_BeginRequest(object sender, EventArgs e)
    HttpContext.Current.Items["renderStartTime"] = DateTime.Now;

Finally, we intercept the request just before it leaves the Http pipeline and get the start date back form the current context. We can then subtract the start time from the current time to give us the approximate duration of the request.

void Application_EndRequest(object sender, EventArgs e)
    DateTime start = (DateTime) HttpContext.Current.Items["renderStartTime"];
    TimeSpan renderTime = DateTime.Now - start;
    HttpContext.Current.Response.Write("<!-- Render Time: " + renderTime + " -->");

At the end of the routine we write the data to the response in a comment so that we can easily see how long the page took by just peeking in the source:

<!-- Render Time: 00:00:00.8713833 -->

Simple I know, but a handy little tip nonetheless. Be aware that this is an approximate render time and doesn't account for anything that occurs in the ASP.NET http pipeline before/after the Global.asax is triggered.


Josh Post By Josh Twist
3:15 AM
24 Apr 2006

» Next Post: Show and Hide tab pages in Windows Forms
« Previous Post: Premature Optimisation

Comments are closed for this post.

Posted by Joel @ 12 Mar 2009 10:13 AM
This is a great tip!
One question though: can I use this method to print out the timer value in the middle of a script, so I can try to find which parts of the page rendering are slow and needs optimization?

If not, do know how to do that?

© 2005 - 2022 Josh Twist - All Rights Reserved.