Wednesday, January 9, 2008

Time taken by a webpage for execution : Page Cost

Following code will help us finding the Time taken by a page for execution i.e. Page CostWe need to use this for testing environment.This will create a log file.
The code calculates the time by calculating the interval between the Application_BeginRequest and Application_EndRequest events.
<%@ import namespace="System.IO" %>
<script runat="server">
//static members for the writing syncronization
private static StreamWriter _writer;
private static object _lock = new object();
//change this to a directory that the aspnet account has read\write //permissions to
private static string _fileName = string.Format(@"c:\temp\log_{0}.txt",DateTime.Now.ToFileTime());
//member variables for tracking start/end times
private DateTime _startTime;
private DateTime _endTime;
public static StreamWriter GetStaticWriter()
{
//make sure we're thread safe here...
if(_writer==null){
lock(_lock){
if(_writer==null){
_writer = new StreamWriter(_fileName,false);
_writer.WriteLine("IP ADDRESS \tSTART TIME \tEND TIME \tDIFF \tURL");
_writer.WriteLine("===============\t============\t============\t================\t=========================");
_writer.Flush();
}
}
}
return _writer;
}
public static void LogText(string str){
GetStaticWriter().WriteLine(str);
GetStaticWriter().Flush();
}
protected void Application_BeginRequest(Object sender, EventArgs e){
_startTime = DateTime.Now;
}
protected void Application_EndRequest(Object sender, EventArgs e){
_endTime = DateTime.Now;
LogText(string.Format("{0,-12}\t{1:hh:mm:ss.fff}\t{2:hh:mm:ss.fff}\t{3}\t{4}",Request.ServerVariables["REMOTE_ADDRESS"].ToString(),_startTime,_endTime,_endTime-_startTime,Request.Url));
}
protected void Application_End(Object sender, EventArgs e){
//release the writer
// Even if this doesn't execute, when the appdomain gets shutdown //it will be released anyways
if(_writer!=null)
_writer.Close();
}
</script>

No comments: