0

I am able to get the frame rate of the Android system using the following answer in Java: https://stackoverflow.com/a/8908035/4190159

However, being new to Kotlin I was wondering how can I get the frame rate of Android system using Kotlin code? (my app is using Kotlin instead of Java)

The code as follows is not working for me:

fun getFrameRate(): String {
        val timeElapsed1: android.os.SystemClock = SystemClock.elapsedRealtime()
        val timeElapsed2: android.os.SystemClock = SystemClock.elapsedRealtime()
        val frameTime = 1000.0 / (timeElapsed2 - timeElapsed1) 
        return frameTime
}
Somdip Dey
  • 3,346
  • 6
  • 28
  • 60
  • You appear to be comparing two time instants one after another, shouldn't you be comparing between two times recorded by different calls of `Choreographer.postFrameCallback()`? – Morrison Chang Jul 13 '22 at 14:50
  • @MorrisonChang Thank you for your reply. I am new to Kotlin development and not sure how to get the framerate. Any suggestions on how to call Choreographer.postFrameCallback() to get framerates? – Somdip Dey Jul 14 '22 at 00:41
  • 1
    I'm not sure what problem you are trying to solve by getting the 'frame rate' of the system. I recommend reviewing the Google IO video: [Drawn out: How Android renders (Google I/O '18)](https://youtu.be/zdQRIYOST64) and [UI Jank Detection](https://developer.android.com/studio/profile/jank-detection) documentation. – Morrison Chang Jul 14 '22 at 02:03

1 Answers1

2

SystemClock.elapsedRealtime() returns a long, not an android.os.SystemClock:

fun getFrameRate(): String {
        val timeElapsed1: Long = SystemClock.elapsedRealtime()
        val timeElapsed2: Long = SystemClock.elapsedRealtime()
        val frameTime = 1000.0 / (timeElapsed2 - timeElapsed1) 
        return frameTime
}

or you can simply omit the types and let Kotlin infer them for you:

fun getFrameRate(): String {
        val timeElapsed1 = SystemClock.elapsedRealtime()
        val timeElapsed2 = SystemClock.elapsedRealtime()
        val frameTime = 1000.0 / (timeElapsed2 - timeElapsed1) 
        return frameTime
}

Lastly, you'll need to convert frameTime to a String:

fun getFrameRate(): String {
        val timeElapsed1 = SystemClock.elapsedRealtime()
        val timeElapsed2 = SystemClock.elapsedRealtime()
        val frameTime = 1000.0 / (timeElapsed2 - timeElapsed1) 
        return frameTime.toString()
}
Egor
  • 39,695
  • 10
  • 113
  • 130
  • Thank you for your reply. Currently, using your code snippet I am getting the following error: "Unresolved reference: SystemClock". :( But was resolved by using android.os.SystemClock instead. However, the output (returned value) of frameTime.toString() is Infinity. – Somdip Dey Jul 13 '22 at 11:31
  • What are the values of `timeElapsed1` and `timeElapsed2`? – Egor Jul 14 '22 at 00:54
  • SystemClock.elapsedRealtime().toString() is coming to Infinity. How to resolve this? – Somdip Dey Feb 18 '23 at 18:30