Monitoring Page Generation and Page Load Time in MVC 3 .Net.

It seems that many post concern .Net development hints do not care about the reader. That’s I decided to write this blog collecting information from difference places and putting together. There are some additional helpful things from me…

This post is intended to show a very simple and comfortable way to monitor web page generation and load time in your web application. It uses a java script and a IHttpModule implementation in MVC 3 .Net environment.

The measurements are divided in 2 : Page Load and Page Generation time.

Page Load Time

Let’s make a short definition of Page Load Time. This is a time showing how long it takes for a page to load. A timer starts when the page begins to parse and ends when it has completed loading all of the content. The measurement of this time is a suitable task for java script implementation. Some examples can be found in Loading Time[1] and Indicator JavaScript Web Page Load Time[2] web publications. Both are based on using JavaScript Timing Events.

Page Generation Time

“Page Generation Time” measure how long it took for a page to be generated by the server. Some short and working examples how to do this in .Net MVC environment can be found in stackoverflow[3] and Pro ASP.NET MVC Framework by Steven Sanderson – Chapter 15 – Performance, Monitoring Page Generation Times[4].

My Implementation

In the following example I made some additions to the above pointed examples to allow page generation and page load times measurement in case of AJAX request.

1 Java Script

Put in a java script file the folloing variables and functions:

  /***************************** TIMER Page Load *******************************/
  var loopTime;
  var startTime = new Date();
  var pageGenerationTime = "0.0";

  function pageloadTimerCount() {
   loopTime = setTimeout("pageloadTimerCount()", 100);
  }

  function pageloadDoTimer() {
       pageloadTimerCount();
  }

  function pageloadStopTimer() {
     var timeMs = Math.floor((new Date() - startTime)); 

     $('#loadtime').html("" + timeMs );
     $('#generatetime').html(pageGenerationTime);
     $('#pagetime').show();

     clearTimeout(loopTime);
  }

2 _Layout.cshtml

2.1 Include Reference of the above JS file

2.2 In the beginning oh HEAD tag include startTime initialization:
  <head>
    <script type="text/javascript">
        var startTime = new Date();
    </script>
    .....
  </head>

2.3 In Page body tag include a similar DIV like this one:
     <div id="pagetime" style="display:none;">
       Page Generation: <span id="generatetime">0.0</span> Page Load: <span id="loadtime">0.0</span> ms.
     </div>

2.4 In the end of page include:
   <script type="text/javascript">
   $(document).ready(function () {pageloadDoTimer();});
    </script>

3 Performance Monitor Module

Create and Register a Custom HTTP Module – PerformanceMonitorModule. The similar modul is described in Pro ASP.NET MVC Framework by Steven Sanderson – Chapter 15 – Performance, Monitoring Page Generation Times[4] and some help reference can be found in in MSDN Library.

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

 namespace Website.Module
 {
   public class PerformanceMonitorModule : IHttpModule
   {
       public void Dispose() { /* Nothing to do */ }
       public void Init(HttpApplication context)
       {
           context.PreRequestHandlerExecute += delegate(object sender, EventArgs e)
           {
               HttpContext requestContext = ((HttpApplication)sender).Context;
               Stopwatch timer = new Stopwatch();
               requestContext.Items["Timer"] = timer;
               timer.Start();
           };
           context.PostRequestHandlerExecute += delegate(object sender, EventArgs e)
           {
               HttpContext requestContext = ((HttpApplication)sender).Context;

               Stopwatch timer = (Stopwatch)requestContext.Items["Timer"];
               timer.Stop();
               // Don't interfere with non-HTML responses 

                   if (requestContext.Response.ContentType == "text/html" ||
                       requestContext.Response.ContentType == "application/json")
                   {

                           Uri requestUrl = requestContext.Request.Url;
                           double ms = (double)timer.ElapsedMilliseconds;
                           string result = string.Format("{0:F0} ms.", ms);

                           requestContext.Response.Write(
                                   "<script type=\"text/javascript\">
                                       var pageGenerationTime = '" + result + "';
                                       pageloadStopTimer();
                                    </script>");

                   }
           };
       }
   }
 }

PerformanceMonitorModule Registration in Web.Config:

 <configuration>
 ...
   <system.web>
   ...
     <httpModules>
       <add name="PerfModule" type="Website.Module.PerformanceMonitorModule, Reports.Website"/>
     </httpModules>
    ...
   </system.web>
 ...
 </configuration>

4 Partial Views

In partial views used for AJAX request put the following in the beginning of the page:

  <script type="text/javascript">
      var startTime = new Date();
  </script>

5 CSS

In my implementation I am using the following css that shows time values under main menu on the page.

  #pagetime
  {
   position: absolute;
   width: 325px;
   left: 55%;
   margin: -22px auto 2px auto;
   z-index:6;
   padding: 2px;
   color: #F47511;
   text-align:center;
   font-size:x-small;
   font-style:italic;
 }

Short Explanation

ASP .Net MVC3

Page Load Time is measured using timing event. When page is loded the variable startTime is set to current time [2.2]. Ondocument.ready event the call to pageloadDoTimer java script function initiate timer loopTime. This timer executes a loop call topageloadTimerCount function on every 100 ms. The timer loop is canseled by calling pageloadStopTimer function. This call is added to alltext/html or application/json request by PerformanceMonitorModule. Time difference betwin startTime and current time is ‘Page Load Time. The following is used to display this value:

  var timeMs = Math.floor((new Date() - startTime));
  $('#loadtime').html("" + timeMs );

Page Generation Time is measured using .NET’s built-in high-resolution timer class, System.Diagnostics.Stopwatc in custom HTTP module (PerformanceMonitorModule). It appends performance statistics to the bottom of each page generated as a java script variablepageGenerationTime. When the pageloadStopTimer function is called pageGenerationTime value is placed in the corresponding place:

   $('#generatetime').html(pageGenerationTime);

 

References

  1.  Abraham Joffe,Loading Time, 2012
  2.  Robert Hashemian,Indicator JavaScript Web Page Load Time,2011
  3.  JOBG,Page generation time – ASP.Net MVC, Dec 1, 2009
  4.   Steven Sanderson,Pro ASP.NET MVC 4 (Professional Apress) , April 30, 2009
  1. Thank you very much for such a helpful and simple explanation with examples.

  2. Ever missed an expiry date? With Expiry Tracker, you can keep all those important dates in one place, at the touch of your screen.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Captcha Captcha Reload