Why measured time inside method is way bigger than inside method?

42 Views Asked by At

Imagine the following:

// added so that it is obvious that this it's not just a delay
inline fun <T> measure(fn: () -> T): T {
    val a = System.currentTimeMillis()
    val r = runCatching { fn() }
    val b = System.currentTimeMillis()
    val seconds = (b - a).toDouble() / 1000.0
    println("Took $seconds to complete")
    return r.getOrThrow()
}


suspend fun doSomething() = ...
suspend fun measureSomething() = measuring{
  doSomething()
} // logs 7 seconds

measuring{
  measureSomething()
} // logs 15 seconds? WHY????

Why the big difference?

I think one of the possible reasons could be that the CoroutineScope is waiting for children scopes to finish...

If that's the case, how can I debug that?

YET, I don't think that's the case. So another reason could be the event loop having little resources, and not releasing the thread until later on when it can... but 8 seconds doing that?

Makes no sense!

0

There are 0 best solutions below