Calculate the execution time of your page ASP. NET

Source: Internet
Author: User

This article describes how to calculate ASP. NET page execution time. When the project is large, sometimes some unknown errors may occur, this may be caused by performance bottlenecks or some bugs (for example, may cause two accesses to your service resources ), in this case, we need to calculate the execution time of each time to sort out the pages that cause project performance exceptions.

 

Step 1: Create a base class for all pages

PageBase. cs

Using System; using System. data; using System. configuration; using System. web; using System. web. security; using System. web. UI; using System. web. UI. webControls; using System. web. UI. webControls. webParts; using System. web. UI. htmlControls; using System. collections. generic; using System. text; using System. IO; /// <summary> /// description of the PageBase abstract /// </summary> public class PageBase: Page {public PageBase () {///TODO: add Add the constructor logic //} # region Overridenprotected override void OnInit (EventArgs e) {base. onInit (e); // calculate the execution time if (this. measureExecutionTime) {watch = new System. diagnostics. stopwatch (); watch. start (); this. recordTimeStamp ("Page execution started ...... ") ;}} Protected override void OnLoad (EventArgs e) {base. onLoad (e);} protected override void OnPreRenderComplete (EventArgs e) {base. onPreRenderComplete (e); if (this. measureExecutionTime) {this. recordTimeStamp ("Page execution complete... "); watch. stop (); Control addExecutionTo = this. form; if (addExecutionTo = null) addExecutionTo = this; addExecutionTo. controls. add (new LiteralControl ("<br/>"); StringBu Ilder timestampsOutput = new StringBuilder (50 * this. excutionTimeStamps. count); for (int I = 0; I <this. excutionTimeStamps. count; I ++) timestampsOutput. appendFormat ("<B> Timestamp {0} </B>: {1: N0} MS ({2}) <br/> {3}", I + 1, this. excutionTimeStamps [I]. timeStamp, this. excutionTimeStamps [I]. description, Environment. newLine); addExecutionTo. controls. add (new LiteralControl (timestampsOutput. toString () ;}# en Dregion # region Members # endregion # region FindControlRecursive iterative lookup Control protected virtual Control FindControlRecursive (string id) {return FindControlRecursive (id, this );} /// <summary> /// iterative search control /// </summary> /// <param name = "id"> Search Control id </param> // /<param name = "parent"> Control container </param> // <returns> Control </returns> protected virtual Control FindControlRecursive (string id, control parent) {// if parent is the co Ntrol we're looking for, return itif (string. compare (parent. ID, id, true) = 0) return parent; // search through childrenforeach (Control child in parent. controls) {Control match = FindControlRecursive (id, child); if (match! = Null) return match;} // if we reach here then no control width id was found. return null ;} # endregion # region ExecutionTime execution time // <summary> // whether to enable computing page computing time /// </summary> public virtual bool MeasureExecutionTime {get {object o = ViewState ["MeasureExecutionTime"]; return o = null? False: (bool) o ;}set {ViewState ["MeasureExecutionTime"] = value ;}} private System. diagnostics. stopwatch watch = null; private List <TimeStampInfo> timeStamps = null; /// <summary> /// set of execution time on the page /// </summary> protected virtual List <TimeStampInfo> ExcutionTimeStamps {get {if (timeStamps = null) timeStamps = new List <TimeStampInfo> (); return timeStamps ;}} /// <summary> /// record the page execution time /// </summary> /// <param name = "desc"> </param> protected virtual void RecordTimeStamp (string desc) {if (watch = null) throw new ArgumentException ("the execution time of the page to be recorded must be set to true. "); ExcutionTimeStamps. add (new TimeStampInfo (watch. elapsedMilliseconds, desc) ;}# endregion}

 
First, use the variable MeasureExecutionTime to save whether the page needs to calculate the execution time, and then rewrite the OnInit event of the page. When the page execution time needs to be calculated, start Stopwatch.
Finally, the calculation result is output in OnPreRenderComplete.
 
Step 2: Create a page to calculate the page execution time
The test on the page is as follows:
Default.aspx.cs
 
using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default :PageBase{protected void Page_Init(object sender, EventArgs e){base.MeasureExecutionTime = true;}protected void Page_Load(object sender, EventArgs e){// Record timestampbase.RecordTimeStamp("Starting long running process");// Do long running processRandom rnd = new Random();System.Threading.Thread.Sleep(rnd.Next(1000) + 1000);if (!IsPostBack){DataTable dt = new DataTable();dt.Columns.Add("ID");dt.Columns.Add("Name");for (int i = 0; i < 20; i++){DataRow dr = dt.NewRow();dr["ID"] = i;dr["Name"] = "Name" + i.ToString();dt.Rows.Add(dr);dt.AcceptChanges();}gv.DataSource = dt;gv.DataBind();}// Record timestampbase.RecordTimeStamp("Completed long running process");}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.