計算出你頁面執行的時間 ASP.NET

來源:互聯網
上載者:User

本文將敘述如何計算出ASP.NET頁面執行所需要的時間,當項目較大的時候有時候可能出現一些莫明其妙的錯誤,這可能是效能上的瓶頸或者是某些BUG引發的(比如<img src="" />,會引起兩次訪問你的服務資源),這時我們需要計算出每個時間執行的時間以便排查出引發項目出現效能異常的頁面。

 

第一步:建立所有頁面的基類

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>/// PageBase 的摘要說明/// </summary>public class PageBase : Page{public PageBase(){//// TODO: 在此處添加建構函式邏輯//}#region Overridenprotected override void OnInit(EventArgs e){base.OnInit(e);//計算時間執行時間if (this.MeasureExecutionTime){watch = new System.Diagnostics.Stopwatch();watch.Start();this.RecordTimeStamp("頁面開始執行……");}}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 /><br />"));StringBuilder 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()));}}#endregion#region Members#endregion#region FindControlRecursive  迭代尋找控制項protected virtual Control FindControlRecursive(string id){return FindControlRecursive(id, this);}/// <summary>/// 迭代尋找控制項/// </summary>/// <param name="id">尋找控制項的編號</param>/// <param name="parent">控制項容器</param>/// <returns>Control</returns>protected virtual Control FindControlRecursive(string id, Control parent){// if parent is the control 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 執行時間/// <summary>/// 是否開啟計算頁面計算時間/// </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>/// 頁面執行時間集合/// </summary>protected virtual List<TimeStampInfo> ExcutionTimeStamps{get {if (timeStamps == null)timeStamps = new List<TimeStampInfo>();return timeStamps;}}/// <summary>/// 記錄頁面執行時間/// </summary>/// <param name="desc"></param>protected virtual void RecordTimeStamp(string desc){if (watch == null)throw new ArgumentException("要記錄頁面的執行時間 MeasureExecutionTime 必須設定為 true.");ExcutionTimeStamps.Add(new TimeStampInfo(watch.ElapsedMilliseconds,desc));}#endregion}

 
首先用一個變數MeasureExecutionTime來儲存頁面是否需要計算出執行的時間,然後重寫頁面的OnInit事件 ,當需要計算頁面執行的時間則啟動Stopwatch。
最後在OnPreRenderComplete中輸出計算的結果。
 
第二步:建立需要計算頁面執行時間的頁面
其頁面的測試如下:
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");}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.