Fork me on GitHub


Android Trace file to flamegraph converter

What are flamegraphs?

Flame graphs are an invention of Brendan Gregg, a profiling extraordinaire, that make it simple to observe the amount of time in each part of a system's call stack. The X axis shows the calls on the stack (alphabetically, not in time order) and the Y axis is the depth of the call stack. The wider the frame, the more time was spent in it and it's descendants. For this tool, the size is directly proportional to the elapsed execution time (in microseconds).
As an example, you can view the trace of an application that performs database calls in the onCreate of an activity here.

How do I generate a trace file?

To gather traces, use the Debug#{start,stop}MethodTracing calls to generate a trace file. Place the call to start tracing before the code under test, and the call to stop tracing directly after. Keeping the profile fairly short will help keep it readable.
If you experience too much of a performance degradation from the tracing overhead to get a good output, you may want to try the startMethodTracingSampling call available on Android APIs 21 and up. It is significantly lower overhead, but due to the nature of a sampling profiler may miss some data.
As an example, here is how one would instrument the onCreate method of an activity in order to determine what is causing slow starts:
private static final int MEGABYTE = 1024 * 1024;

protected void onCreate(Bundle savedInstanceState) {
    // Call the resulting trace file 'onCreate.trace', and allow a 128MiB
    // buffer for collecting trace data.
    Debug.startMethodTracing("onCreate", 128 * MEGABYTE);
    // Existing onCreate code
    // Stop method tracing

I'd like to know more

Feel free to read either the write-up I have on the format of the trace file and how it is converted to a format the flamegraph tool understands, or read the source on Github to see for yourself.