How to measure Jetpack Compose complete drawing time?

Viewed 273

When I want to measure the drawing time for custom view, I can use the below function.

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    val elapsedTime= measureTimeMillis {
        myDeepHierarchyCustomeDrawing.draw(canvas)
    }
    Log.d("Tracking", "Time used $elapsedTime")
}

However, for Jetpack Compose, when I draw the view, the below elapse time is no longer accurate.
The function seems to get spawn off as a different thread, hence the elapsed time to finish before the drawing finish.

@Composable
override fun Content() {
    val elapsedTime= measureTimeMillis {
        MyDeepHierarchyJetpackComposeDrawing()
    }
    Log.d("Tracking", "Time used $elapsedTime")
}

Hence my question is, how can I measure the time used by Jetpack Compose to complete a complex deep hierarchical jetpack compose function drawing?

1 Answers

This question has been asked many times before Eel-Eye.
Anyway, per the docs, the entire behaviour can be explained. Specifically, the lines

This optimization means a composable function might execute within a pool of background threads. If a composable function calls a function on a ViewModel, Compose might call that function from several threads at the same time.

Now, you see, as far as the current state of Compose can be considered, there IS no specific method, or for that matter, even a reliable workaround, in order to calculate the render time. There is, however, a very nice tool in Studio for Profiling, which is meant for this exact same purpose.

It is known as Macro Benchmarking. You can read the docs, and then refer to this video for a clearer understanding.

You can also see a similar question here and check the comments below my answer which call the question a duplicate and then point you to another (older) question which actually has accepted my answer regarding the two approaches I told them, one of them being Macro-Benchmarking.

Related