Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

Xamarin.Forms Profiling

David Britch edited this page Jul 23, 2020 · 2 revisions

Before doing any profiling with this API, you probably can have a look at what the individual platforms have because they will have far more data and numbers:

But, back to Xamarin.Forms APIs that may be useful in other scenarios...

There are two parts to this:

API

namespace Xamarin.Forms.Internals
{
    public struct Profile
    {
        // control
        
        // enable the profiler
        public static void Enable();
        // start profiling from here, only if enabled
        public static void Start();
        // stop the profiling
        public static void Stop();
        
        // instrumentation
        
        // start a new frame in the profiling
        public static void FrameBegin();
        // mark a step in the current frame
        public static void FramePartition(string id);
        // end the current frame
        public static void FrameEnd();
    }
    
    public static class ContentPageEx
    {
        // replace the current page with the profiling results
        // this will also stop profiling
        public static void LoadProfile(this ContentPage page);
    }
}

Usage

The first thing to do is to enable it in whatever the startup location is. In most cases you can start up the profiler before calling the Forms.Init() logic:

using Xamarin.Forms.Internals;

// ...

Profile.Enable();
Profile.Start();

// ...

Forms.Init();

Once the profiler is enabled, you can start instrumenting:

// start in a method
Profile.FrameBegin();
// ...

// start some chunk
Profile.FramePartition("step 1");
// start some chunk
Profile.FramePartition("step 2");

// start a new, sub-setp
Profile.FrameBegin();
// start some chunk
Profile.FramePartition("step 2a");
// start some chunk
Profile.FramePartition("step 2b");
// start some chunk
Profile.FramePartition("step 2c");

// done with the sub-step
Profile.FrameEnd();

// some more work
Profile.FramePartition("step 3");

// all done
Profile.FrameEnd();

Once you are ready to view the numbers, there is an extension method for all ContentPage types.

One thing would be to push a new page or something. In the constructor:

this.LoadProfile();

This will replace everything in that page with the information with a simple UI.

The information will be in the format:

Profiled: 440ms
MethodName = 81ms, 18%
MethodName (step 1) = 10ms, 2%
MethodName (step 2) = 71ms, 16%
  MethodName = 12ms, 1%
  MethodName (step 2a) = 4ms, 1%
  MethodName (step 2b) = 4ms, 1%
  MethodName (step 2c) = 4ms, 1%
MethodName (step 3) = 71ms, 16%