Duration measureTime lag?

Hi,

I found a MeasureTime function in Kotlin its experimental.

That function gets a Block and measure the time of execution

How ever the measures seems to be completly uncorrect when i use the old java way of System.getNanotime i get complety different results in nanoseconds area while the MeasureTime gives me alway Ms even for simple tasks like doing NOTHING

measureTimeMillis uses currentTimeMillis to measure the time. It’s not properly documented in kotlin but this time is not super accurate, depending on the os implementation. If you need better results for timing you should use nanoTime instead which uses the far more accurate timing implementation of the JVM. In kotlin you can use measureNanoTime for that.

I’ve reproduced this situation with measureTime: it returns a duration value of several milliseconds order of magnitude on the first invocation, however subsequent calls should yield values comparable with ones returned from measureNanoTime.

Such overhead on the first invocation can be attributed to the initialization of Clock, ClockMark, and Duration classes. In the following example uncommenting the first line has a big effect on the subsequent measureTime call results.

import kotlin.time.*
fun main() {
//    MonoClock.markNow().elapsedNow()
    repeat(10) {
    	println(measureTime {})
    }
}

We’ll see how that cost of a first-time initialization can be moved out of the first-time measurement.

Thank you i will wait for a futue release so that i replace my methods with the standard Kotlin ones, by the Way I think a good practice would be to measure multiple Time and make an average Value to be more precise.