Measure elapsed time in Kotlin
This article explores different ways to measure the elapsed time of the program in Kotlin.
1. Using System.nanoTime() function
The recommended approach to measure the elapsed time of the program in Kotlin is with System.nanoTime(), which returns the current value of JVM’s time source with nanosecond precision.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main() { val begin = System.nanoTime() /* code starts */ // sleep for 2 seconds Thread.sleep(2000) /* code ends */ val end = System.nanoTime() println("Elapsed time in nanoseconds: ${end-begin}") } |
2. Using System.currentTimeMillis() function
You can also measure the elapsed time with System.currentTimeMillis(), but the results might not be that accurate.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val begin = System.currentTimeMillis() /* code starts */ // sleep for 2 seconds Thread.sleep(2000) /* code ends */ val end = System.currentTimeMillis() println("Elapsed time in milliseconds: ${end-begin}") } |
Here’s alternative solution using Instant.now() which internally uses System.currentTimeMillis().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.time.Instant fun main() { val begin = Instant.now().toEpochMilli() /* code starts */ // sleep for 2 seconds Thread.sleep(2000) /* code ends */ val end = Instant.now().toEpochMilli() println("Elapsed time in milliseconds: ${end-begin}") } |
3. Using Date.getTime() function
The Date class also offers the getTime() function that returns the milliseconds’ number since epoch. We can also use this to measure elapsed time in Kotlin, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Date fun main() { val begin = Date().time /* code starts */ // sleep for 2 seconds Thread.sleep(2000) /* code ends */ val end = Date().time println("Elapsed time in milliseconds: ${end-begin}") } |
That’s all about measuring elapsed time in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)