【问题标题】:How can I most accurately calculate the execution time of an ASP.NET page while also displaying it on the page如何最准确地计算 ASP.NET 页面的执行时间,同时在页面上显示它
【发布时间】:2010-03-23 14:19:39
【问题描述】:
我想计算我的 ASP.NET 页面的执行时间并将其显示在页面上。目前我正在使用 System.Diagnostics.Stopwatch 计算执行时间,然后将值存储在日志数据库中。
秒表在 OnInit 中启动并在 OnPreRenderComplete 中停止。这似乎工作得很好,并且执行时间与页面跟踪中显示的时间相似。
现在的问题是我无法在页面上显示执行时间,因为秒表在生命周期中停止得太晚了。
最好的方法是什么?
【问题讨论】:
标签:
asp.net
performance
page-lifecycle
diagnostics
【解决方案1】:
Here 重新定义 Page_Init() 和 Page_preRender() 方法以获取时间差异的有效解决方案。
private int startTime;
protected void Page_Init(object sender, EventArgs e)
{
startTime = Environment.TickCount;
}
protected void Page_PreRender(object sender, EventArgs e)
{
int endTime = Environment.TickCount;
double executionTime = (double)(endTime - startTime) / 1000.0;
lblLabel.Text = "Page Execution time is " + executionTime + " seconds.";
}
【解决方案2】:
我会在渲染期间从秒表获取经过的时间。此时页面执行时间的大部分(可能几乎全部)已经过去。继续并停止您现在所在的秒表并使用该号码登录到您的数据库。我敢打赌,它与页面上显示的内容不会有太大不同。
【解决方案3】:
将执行时间信息保存到服务器(数据库、文件系统、缓存),然后使用 ajax 或 jquery 将其从服务器异步拉入页面的某个区域。