Consider the following code for measuring request/response times in an Asp.Net application:
protected void Application_EndRequest()
{
Trace.WriteLine(string.Format("{0}:{1}",
(DateTime.Now - HttpContext.Current.Timestamp).TotalMilliseconds,
HttpContext.Current.Request.RawUrl));
}
According to MSDN, DateTime.Now
has an approximate resolution of 10 milliseconds.
Also, from MSDN HttpContext.Timestamp description,
The timestamp returned from the
Timestamp
property is the local time of the server and is set during the instantiation of theHttpContext
object. The local time is equal to the UTC time plus the UTC offset.
The above code should in theory then give me the total request/response time in milliseconds.
My question is, how accurate is this going to be? And is there a more accurate / better way of going about it?
Handlers are responsible for generating the actual response in MVC. They implement the IHttpHandler class and only one handler will execute per request. On the other hand, HttpModules are created in response to life cycle events. Modules can, for example, be used for populating HttpContext objects.
You could try using the miniProfiler in your code, I've found it is pretty neat and useful:
http://miniprofiler.com/
The StopWatch class can potentially have accuracy down to microseconds depending on the hardware and operating system. There is a IsHighResolution property to read if you're in high resolution mode. If not then your are down to the accuracy of system timer.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
The up side of using this class is you will certainly be no worse that the code above. If on hi-res, you'll get much more accuracy.
But, if you're trying to measure performance and get better insight into your service, then there are better tools.
For example, perfview is a good tool:
http://blogs.msdn.com/b/dotnet/archive/2012/10/09/improving-your-app-s-performance-with-perfview.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With