Susheel
07/27/2024, 4:09 AMFrameRateTracker
I'm using this to measure and track framerate for our composables and we report them using our telemetry events. This is to improve UI rendering performance based on the analytics.
Can someone look at the code and tell me if I'm missing something that's supposed to be an edge case?Susheel
07/27/2024, 4:09 AM@Composable
fun FrameRateTracker(modifier: Modifier = Modifier) {
var fps by remember { mutableStateOf(0f) }
var frameCount by remember { mutableStateOf(0) }
var lastFrameTime by remember { mutableStateOf(0L) }
// This effect will run when the composable enters the composition
// and stop when it leaves the composition
LaunchedEffect(Unit) {
while (isActive) {
withFrameNanos { frameTimeNanos ->
if (lastFrameTime != 0L) {
val frameTime = frameTimeNanos - lastFrameTime
frameCount++
if (frameTime >= 1_000_000_000) { // 1 second in nanoseconds
fps = frameCount.toFloat() * 1_000_000_000 / frameTime
frameCount = 0
}
}
lastFrameTime = frameTimeNanos
}
}
}
Box(modifier = modifier) {
Text(
text = "FPS: %.1f".format(fps),
color = Color.Red,
fontSize = 16.sp
)
}
}
romainguy
07/27/2024, 4:45 AMArjan van Wieringen
07/27/2024, 6:19 AMSusheel
07/27/2024, 12:47 PMSusheel
07/27/2024, 1:37 PMromainguy
07/27/2024, 3:11 PM