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
Leave a comment ?

23 Comments.

  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.

  3. Terrific work! This is the type of info that are meant to be shared across the web. Shame on the search engines for now not positioning this publish higher! Come on over and talk over with my site . Thank you =)

  4. Hello would you mind stating which blog platform you’re using? I’m planning to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!

  5. Hello, its good article on the topic of media print, we all know media is a fantastic source of information.

  6. You should be a part of a contest for one
    of the finest websites on the internet. I am going to highly recommend
    this blog!

  7. You need to take part in a contest for the most effective blogs on the web. I will advocate this site!

  8. I have to show my thanks to this writer just for bailing me out of this particular condition. As a result of looking out through the the net and meeting notions which are not powerful, I was thinking my entire life was well over. Living without the presence of strategies to the difficulties you’ve fixed by means of your entire website is a serious case, as well as the kind that could have badly affected my career if I had not discovered the blog. Your good capability and kindness in handling all areas was valuable. I’m not sure what I would’ve done if I hadn’t encountered such a point like this. I can at this moment relish my future. Thanks a lot very much for this high quality and amazing help. I won’t think twice to refer your site to any individual who needs and wants guidance on this topic.

  9. I must express my thanks to the writer just for bailing me out of this setting. Right after searching throughout the internet and coming across proposals which are not beneficial, I was thinking my entire life was gone. Living without the presence of answers to the problems you have sorted out through your good posting is a serious case, as well as the ones which may have in a negative way affected my career if I hadn’t encountered the blog. Your own competence and kindness in maneuvering everything was very helpful. I don’t know what I would’ve done if I hadn’t come upon such a thing like this. I am able to at this point relish my future. Thank you very much for the impressive and results-oriented guide. I won’t hesitate to refer the sites to anybody who ought to have guidance on this topic.

  10. Thank you a lot for giving everyone an exceptionally pleasant opportunity to check tips from this blog. It is often so beneficial plus jam-packed with amusement for me and my office friends to search your web site minimum thrice in 7 days to find out the new guidance you will have. Not to mention, we are actually astounded with all the excellent things served by you. Some 2 areas in this post are unequivocally the most impressive we have ever had.

  11. I have to voice my affection for your generosity giving support to people who absolutely need help with this one situation. Your personal commitment to passing the message throughout appeared to be astonishingly powerful and have in every case helped guys just like me to arrive at their aims. Your new useful help entails a whole lot a person like me and especially to my fellow workers. Warm regards; from each one of us.

  12. You must participate in a contest for probably the greatest blogs on the web. I’ll suggest this site!

  13. Thank you a lot for providing individuals with an extremely wonderful possiblity to read critical reviews from here. It’s always so sweet and stuffed with amusement for me personally and my office colleagues to search your website more than 3 times per week to read through the new items you have got. And of course, I am also usually astounded concerning the unbelievable creative concepts served by you. Some 2 ideas on this page are certainly the most efficient we have ever had.

  14. I precisely had to appreciate you all over again. I am not sure the things that I would’ve gone through without the actual smart ideas provided by you concerning such question. It actually was a very depressing scenario for me personally, nevertheless coming across a expert way you treated that forced me to cry over gladness. Now i am happier for the support and thus believe you realize what an amazing job you happen to be doing training the others by way of your webblog. More than likely you have never met all of us.

  15. I together with my pals were actually reading through the great pointers found on the website while unexpectedly I got a terrible feeling I had not expressed respect to the web blog owner for those strategies. Most of the young men happened to be for this reason stimulated to see them and have in effect unquestionably been tapping into these things. We appreciate you actually being really helpful and then for getting some great themes most people are really eager to understand about. My very own sincere regret for not expressing appreciation to you sooner.

  16. I intended to create you a tiny note in order to thank you once again with your wonderful things you’ve discussed in this case. It’s certainly wonderfully open-handed with people like you to supply openly all many of us could possibly have marketed as an e book to help make some money for themselves, even more so since you might well have tried it if you decided. These secrets also served as a great way to know that some people have a similar keenness really like my own to learn a lot more with respect to this matter. I am certain there are some more fun periods up front for people who look into your blog.

  17. I simply wanted to thank you very much once more. I am not sure what I would’ve achieved in the absence of these smart ideas shown by you relating to my subject matter. Entirely was a traumatic condition for me, but seeing this specialised strategy you processed that took me to jump with delight. I’m just happier for the service and trust you find out what a great job that you are getting into training many people thru your webblog. I’m certain you haven’t met all of us.

  18. My husband and i felt so thankful when Raymond managed to deal with his web research through your ideas he was given through your web site. It’s not at all simplistic to just continually be making a gift of thoughts that many some others have been selling. And we also do understand we have the blog owner to appreciate for that. All the explanations you have made, the easy website menu, the relationships you will help foster – it’s got mostly fantastic, and it’s really assisting our son and the family know that that theme is thrilling, and that is extraordinarily vital. Many thanks for the whole lot!

  19. I wish to get across my affection for your kind-heartedness in support of women who should have help on that content. Your special dedication to passing the message up and down ended up being unbelievably advantageous and has really enabled some individuals much like me to realize their targets. Your amazing insightful instruction denotes this much a person like me and a whole lot more to my colleagues. Warm regards; from everyone of us.

  20. I precisely had to thank you very much once more. I am not sure the things I would’ve created without the type of tricks discussed by you about my theme. It had been a real hard issue in my opinion, but observing this expert tactic you processed that forced me to jump over happiness. Extremely happier for your advice and then believe you find out what a powerful job your are carrying out educating many others via your webblog. Probably you’ve never encountered all of us.

  21. Thanks for all of your effort on this blog. My mom really loves working on internet research and it’s obvious why. Most people learn all about the powerful manner you produce sensible tips and tricks by means of this web site and boost response from visitors on that matter then our daughter is in fact starting to learn a whole lot. Take advantage of the remaining portion of the new year. You’re the one conducting a wonderful job.

  22. Thank you so much for providing individuals with an extraordinarily pleasant chance to read articles and blog posts from this site. It’s usually very pleasing and also jam-packed with a good time for me and my office colleagues to search your web site more than three times every week to learn the new secrets you will have. And definitely, I am just always happy considering the mind-blowing opinions served by you. Some 1 tips in this posting are ultimately the simplest we have all had.

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>