https://kotlinlang.org logo
#getting-started
Title
# getting-started
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
Copy code
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
Copy code
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
Copy code
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
Copy code
val result: Int
val timeInMillis = measureTimeMillis {
    result = 1
}
👍 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.
18 Views