Search code examples
c#mvc-mini-profiler

How can I add startup timings to MiniProfiler?


I want to time Application_OnStart using MiniProfiler. So far I've been unsuccessful. I tried to create a Timing and add it to the children of the root, but it doesn't collect all the data I want. It also subtracts the startup time from the overall profile time so it ends up with a negative duration. Currently the only solution I have is timing it myself with a stopwatch and adding it to client timings. This removes the client timings from the first request and adds the application startup duration. But I don't gain custom timings, etc. Also since I use the AddProfilerResults method to combine my API profiles within my MVC profiles (for the MVC UI, they are wrapped in steps), the startup time for the API on the first MVC request isn't included, and it's basically lost.

            MiniProfiler.Current.ClientTimings = new ClientTimings
            {
                Timings = new List<ClientTimings.ClientTiming>
                {
                    new ClientTimings.ClientTiming
                    {
                        Duration = startTime,
                        Id = Guid.NewGuid(),
                        MiniProfilerId = Guid.NewGuid(),
                        Name = "Application_Start",
                        Start = 0
                    }
                }
            };

Solution

  • The way we do it here on Stack Overflow is to create a MiniProfiler in the startup method, add steps to it, then render it to a static string:

    public static string ApplicationStartTimings { get; private set; }
    
    protected void Application_Start(object sender, EventArgs e)
    {
        // init MiniProfiler.Settings here
        // ...
        var prof = new MiniProfiler("Application_Start");
    
        using (prof.Step("Register routes"))
        {
            RegisterRoutes(RouteTable.Routes);
        }
    
        // ... more config and steps
    
        try
        {
            ApplicationStartTimings = prof.Render().ToString();
        }
        catch { }
    }
    

    You can then have a route to display these timings. It's hacky, but gets the job done.

    Edit - I added a branch to my MiniProfiler fork which demonstrates this working; here's the output on the main index page:

    enter image description here