https://kotlinlang.org logo
Title
n

Nicola

03/30/2023, 1:32 PM
Which is the best way to measure elapsed time in executing a function? Now I would go with something like this
val start = System.nanoTime()
execute_my_function()
val duration = System.nanoTime() - start
Would it be ok or are there better ways?
m

mkrussel

03/30/2023, 1:36 PM
Kotlin has some built in functions
measureTime
,
measureTimeInNanos
,
measureTimedValue
. You pass a block into the measure functions and they will return how long it took.
v

Vampire

03/30/2023, 1:36 PM
val duration = measureTime {
    execute_my_function()
}
n

Nicola

03/30/2023, 1:39 PM
Thanks, but does it work even when the function returns a value to the caller? eg
val startTime = System.nanoTime()
val response = execute_my_function()
val duration = System.nanoTime() - startTime
(forgot this detail)
i'll try
Ah but that api needs opt-in experimental feature, doesn'it ?
m

mkrussel

03/30/2023, 1:50 PM
The one that returns a
Duration
needs an opt in. The
measureTimeInNanos
don't. To get a value, use the one that has value in the name.
v

Vampire

03/30/2023, 1:50 PM
It does, if you don't like that, use
measureTimeMillis
Or to also support return value
measureTimedValue
m

mkrussel

03/30/2023, 1:52 PM
Actually I can only find a Value version for the experimental time.
v

Vampire

03/30/2023, 1:52 PM
yes
n

Nicola

03/30/2023, 2:01 PM
measureTimeMillis
ok thanks a lot!
v

Vampire

03/30/2023, 2:02 PM
For non-experimental, you can just set the result property in the lambda that you defined before like shown in the docs
val result: Int
val timeInMillis = measureTimeMillis {
    result = 1
}
n

nkiesel

03/31/2023, 11:22 PM
I personally would opt-in to
measureTimedValue
: unlikely to change, and nicer to use that breaking up definition and assignment. And if you want to control the potential impact, then create your own wrapper and use that in your code.