What is the best way to measure the code run time in ASP.NET page?
Here is my code, trying to time the page load and writing to log.
private Stopwatch PageTimer = null;
protected void Page_Init(Object Src, EventArgs E)
{
if (!IsPostBack)
{
PageTimer = new Stopwatch();
PageTimer.Start();
}
}
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
PageTimer.Stop();
Logger.SectionEnd("PageTimer", PageTimer, "", true);
}
base.OnPreRender(e);
}
I’d recommend you use a HttpModule for that. There’s one you can use at
HttpModule For Timing Requests
(pretty old, I know, but still valid)
A good thing about HttpModules is that you have them self-register themselves if the “main application” has code for it. Using a module in another application is then just a copy paste in to the bin folder and it will start to operate.
If the “main application” doesn’t support modules to self-register it can be added to the bin and web.config to start operating.