Which is the best way to measure elapsed time in e...
# getting-started
n
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
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
Copy code
val duration = measureTime {
    execute_my_function()
}
n
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
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
It does, if you don't like that, use
measureTimeMillis
Or to also support return value
measureTimedValue
m
Actually I can only find a Value version for the experimental time.
v
yes
n
Copy code
measureTimeMillis
ok thanks a lot!
v
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
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.