The ViewContext.HttpContext.Timestamp
thing as suggested by Marnix is clever, I hadn't realised that was there. However, you could also do it as an HttpModule which would work in non MVC application too:
using System;
using System.Web;
namespace MyLibrary
{
public class PerformanceMonitorModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.PreSendRequestContent += delegate(object sender, EventArgs e)
{
HttpContext httpContext = ((HttpApplication)sender).Context;
if (httpContext.Response.ContentType == "text/html")
{
DateTime timestamp = httpContext.Timestamp;
double seconds = (double)DateTime.Now.Subtract(timestamp).Ticks / (double)TimeSpan.TicksPerSecond;
string result = String.Format("{0:F4} seconds ({1:F0} req/sec)", seconds, 1 / seconds);
httpContext.Response.Write("<div style=\"position: fixed; right: 5px; bottom: 5px; font-size: 15px; font-weight: bold;\">Page Execution Time: " + result + "</div>");
}
};
}
}
}
Then put this into your web.config:
<httpModules>
<!-- Other httpModules (snip) -->
<add name="PerformanceMonitor" type="MyLibrary.PerformanceMonitorModule, MyLibrary"/>
</httpModules>
This will record the time at the very last moment it gets before sending the HTML content to the browser so that it is measuring as much of the HTTP pipeline as possible. Not sure if sticking ViewContext.HttpContext.Timestamp in the page markup can achieve this?
Note: this won't produce valid HTML markup because it spits a <div>
to the bottom of the page, so only use for development/performance analysis.
EDIT: I modified the HttpModule to use HttpContext.Timestamp instead of storing a Stopwatch object in the Request context, as it seems to give more accurate results.