Time measurement
The Kotlin standard library gives you the tools to calculate and measure time in different units. Accurate time measurement is important for activities like:
Managing threads or processes
Collecting statistics
Detecting timeouts
Debugging
By default, time is measured using a monotonic time source, but other time sources can be configured. For more information, see Create time source.
Calculate duration
To represent an amount of time, the standard library has the Duration
class. A Duration
can be expressed in the following units from the DurationUnit
enum class:
NANOSECONDS
MICROSECONDS
MILLISECONDS
SECONDS
MINUTES
HOURS
DAYS
A Duration
can be positive, negative, zero, positive infinity, or negative infinity.
Create duration
To create a Duration
, use the extension properties available for Int
, Long
, and Double
types: nanoseconds
, microseconds
, milliseconds
, seconds
, minutes
, hours
, and days
.
For example:
You can also perform basic arithmetic with Duration
objects:
Get string representation
It can be useful to have a string representation of a Duration
so that you can print, serialize, transfer, or store it.
To get a string representation, use the .toString()
function. By default, the time is reported using each unit that is present. For example: 1h 0m 45.677s
or -(6d 5h 5m 28.284s)
To configure the output, use the .toString()
function with your desired DurationUnit
and number of decimal places as function parameters:
To get an ISO-8601-compatible string, use the toIsoString()
function:
Convert duration
To convert your Duration
into a different DurationUnit
, use the following properties:
inWholeNanoseconds
inWholeMicroseconds
inWholeSeconds
inWholeMinutes
inWholeHours
inWholeDays
For example:
Alternatively, you can use your desired DurationUnit
as a function parameter in the following extension functions:
.toInt()
.toDouble()
.toLong()
For example:
Compare duration
To check if Duration
objects are equal, use the equality operator (==
):
To compare Duration
objects, use the comparison operators (<
, >
):
Break duration into components
To break down a Duration
into its time components and perform a further action, use the overload of the toComponents()
function. Add your desired action as a function or lambda expression as a function parameter.
For example:
In this example, the lambda expression has hours
and minutes
as function parameters with underscores (_
) for the unused seconds
and nanoseconds
parameters. The expression returns a concatenated string using string templates to get the desired output format of hours
and minutes
.
Measure time
To track the passage of time, the standard library provides tools so that you can easily:
Measure the time taken to execute some code with your desired time unit.
Mark a moment in time.
Compare and subtract two moments in time.
Check how much time has passed since a specific moment in time.
Check whether the current time has passed a specific moment in time.
Measure code execution time
To measure the time taken to execute a block of code, use the measureTime
inline function:
To measure the time taken to execute a block of code and return the value of the block of code, use inline function measureTimedValue
.
For example:
By default, both functions use a monotonic time source.
Mark moments in time
To mark a specific moment in time, use the TimeSource
interface and the markNow()
function to create a TimeMark
:
Measure differences in time
To measure differences between TimeMark
objects from the same time source, use the subtraction operator (-
).
To compare TimeMark
objects from the same time source, use the comparison operators (<
, >
).
For example:
To check if a deadline has passed or a timeout has been reached, use the hasPassedNow()
and hasNotPassedNow()
extension functions:
Time sources
By default, time is measured using a monotonic time source. Monotonic time sources only move forward and are not affected by variations like timezones. An alternative to monotonic time is elapsed real time which is also known as wall-clock time. Elapsed real time is measured relative to another point in time.
Default time sources per platform
This table explains the default source of monotonic time for each platform:
Platform | Source |
---|---|
Kotlin/JVM |
|
Kotlin/JS (Node.js) |
|
Kotlin/JS (browser) |
|
Kotlin/Native |
|
Create time source
There are some cases where you might want to use a different time source. For example in Android, System.nanoTime()
only counts time while the device is active. It loses track of time when the device enters deep sleep. To keep track of time while the device is in deep sleep, you can create a time source that uses SystemClock.elapsedRealtimeNanos()
:
Then you can use your time source to make time measurements:
For more information about the kotlin.time
package, see our standard library API reference.