Measuring Code Execution Time with Kotlin’s measureTimedValue

As Kotlin developers, optimizing the performance of our code is essential. One of the simplest ways to assess performance is by timing how long certain code blocks take to execute. With Kotlin’s measureTimedValue function, you can easily measure execution time while also obtaining the result of your function.
To time a block of Kotlin code and keep its result, wrap it in measureTimedValue { } from kotlin.time: you get back a TimedValue whose value is the block's result and whose duration is a Duration. If you only need the elapsed time, use measureTime { } instead. Both are stable since Kotlin 1.9.0 and run on a monotonic clock, so system clock changes do not skew the number.

What is measureTimedValue?
The measureTimedValue function, introduced in Kotlin 1.9, allows you to execute a block of code and returns both the result of that block and the time it took to execute. This function can be extremely helpful for benchmarking certain parts of your application, allowing you to optimize slow or resource-intensive sections.
For example:
val result = measureTimedValue {
longRunningOperation()
}
println("Result: ${result.value}, Time: ${result.duration}")In this example, the function longRunningOperation() is wrapped in measureTimedValue. The output includes both the result of the operation and the duration it took to execute.
How Does It Work?
The measureTimedValue function internally uses TimeSource.Monotonic, which provides a precise and non-adjustable time measurement. This ensures that external factors like system clock changes don’t affect the measurement.
Example: Measuring Code Execution
Let’s consider a scenario where you want to measure how long it takes to print two million dots to the console:
fun longRunningOperation(): String {
repeat(2_000_000) { print(".") }
return "Done"
}
fun main() {
val result = measureTimedValue {
longRunningOperation()
}
println("\nOperation took ${result.duration} to calculate: ${result.value}")
}Output:
.........................................
(Operation continues printing dots)
.........................................
Operation took 4.7s to calculate: DoneThis simple code snippet prints dots, then displays the time it took to perform the task along with the result. It’s a straightforward way to ensure you know exactly how long each operation takes, which can be vital when optimizing performance.
Common Use Cases
Developers often use measureTimedValue when benchmarking algorithms or when they need to test the performance of complex operations. Here are a few examples:
Calculating the time taken to fetch data from a database.
Measuring the duration of a network request.
Timing computationally expensive algorithms or functions.
Real-Time Applications
If you’re working with real-time systems, like fetching data from a server or running complex algorithms, you may want to track performance. For example, developers working with Firebase Storage may want to time their data upload process. With measureTimedValue, you can easily track how long these operations take and optimize accordingly.
Advanced Features of Kotlin Time API
In addition to measureTimedValue, the Kotlin Time API offers several other methods for measuring code execution time, including measuring time in milliseconds or nanoseconds. These options don’t return the function result, but they are great for specific use cases where only the time duration is required.
Working with TimeSource
If you want more control over how time is measured, you can use TimeSource. For example, you can replace the default TimeSource.Monotonic with your custom implementation if needed:
val timeSource = TimeSource.Monotonic
val result = timeSource.measureTimedValue {
performTask()
}
println("Task completed in ${result.duration}")For a more detailed explanation on Kotlin’s multiplatform capabilities, including time-related APIs, visit Kotlin Multiplatform.
Conclusion: When to Use measureTimedValue
Timing your code can be crucial for improving your app’s performance, especially when working on larger projects with heavy operations. The measureTimedValue function is an effective tool for doing this in Kotlin, offering both a performance benchmark and the ability to retain the function result.
If you’re looking for additional performance optimization techniques, consider checking out the Android GraphQL with Kotlin Coroutines guide, which offers insights into improving efficiency in Android apps using coroutines and GraphQL.
measureTimedValue vs measureTime vs measureTimeMillis
Kotlin gives you several ways to time code, and the right one depends on whether you need the result and what type you want the time in.
measureTimedValue { } (kotlin.time): returns TimedValue with value and duration. TimedValue is a data class, so you can destructure it: val (user, took) = measureTimedValue { repository.loadUser(id) }.
measureTime { } (kotlin.time): returns only a Duration. Use it when the block is called for its side effect, such as writing a file.
measureTimeMillis { } and measureNanoTime { } (kotlin.system): older helpers that return a plain Long. They still work on JVM and Android, but you lose the Duration type and have to remember which unit the number is in.
TimeSource.Monotonic.markNow(): takes a time mark you can check later with elapsedNow(). This is the option when start and end are not inside one block, for example a request started in one callback and finished in another.
Timing suspend functions and coroutines
measureTimedValue and measureTime are inline functions, so you can call suspend functions inside the block as long as you are already in a coroutine. The measured duration is wall-clock time: it includes the time the coroutine spent suspended, waiting for the network or a delay, not only CPU work. That is usually what you want for a network request or a database query, but keep it in mind when two calls run concurrently and you compare their numbers. If you are new to how suspension works, the Kotlin coroutines guide covers it.
Reading and logging the Duration
Printing a Duration gives a readable value such as 4.7s, as in the example above. When you need a fixed unit, for logs you want to compare or for analytics, convert it explicitly:
duration.inWholeMilliseconds returns a Long in milliseconds.
duration.toString(DurationUnit.MILLISECONDS, 2) prints the value in milliseconds with two decimals.
On Android, send the value to Logcat with a fixed tag, for example Log.d("Timing", "loadUser took ${took.inWholeMilliseconds} ms"), and filter by that tag. The Logcat debugging tips post shows how to filter efficiently.
Why your numbers might be misleading
A single measureTimedValue call tells you how long one run took on one device. It is good for finding the slow step in a flow, but it is not a benchmark. Watch out for these before drawing conclusions:
Console output dominates. In the two-million-dots example, most of the 4.7s is spent printing to the console, not in your own logic. Remove logging from the block you measure.
First run is slower. On the JVM, code is interpreted first and compiled later, and on Android the first call can also include class loading. Run the block a few times and look at the later runs.
Debug builds are not release builds. A debuggable Android build without R8 optimisation can be noticeably slower. Measure on a release build on a real device before you optimise.
One run is noise. Garbage collection or another app can slow a single run. Repeat the measurement and compare the typical value, not the best or the worst one.
When you need repeatable numbers for small pieces of code, use a benchmarking tool instead: kotlinx-benchmark (built on JMH) for JVM code, or the Jetpack Microbenchmark library for code that must run on an Android device. They handle warm-up and repetition for you.
Testing time-dependent code with TestTimeSource
If your own code uses a TimeSource, for example a timeout or a cache that expires, you can make it testable by passing the TimeSource in instead of using TimeSource.Monotonic directly. In tests, pass a TestTimeSource and move time forward by hand with testTimeSource += 5.seconds. The test then checks the timeout logic without actually waiting, and the result is the same on every run.
Performance optimization is a regular part of the freelance Android work I do. If an app of yours has a slow screen or startup and you want a second pair of eyes on it, you can get in touch.
