Last active
October 3, 2023 18:43
-
-
Save rocketraman/e24c5f312538d002f77a84bea7a3c4dd to your computer and use it in GitHub Desktop.
Testing resolution of kotlinx coroutines delay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.coroutineScope | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import kotlin.time.measureTime | |
suspend fun main() { | |
suspend fun delayLoop(delayMillis: Long, delayCount: Int) { | |
var totalDelay: Long = 0 | |
var maxDelay: Long = 0 | |
repeat(delayCount) { | |
measureTime { | |
delay(delayMillis) | |
}.also { | |
val uSecs = it.inWholeMicroseconds | |
totalDelay += uSecs | |
if (uSecs > maxDelay) maxDelay = uSecs | |
} | |
} | |
println("Expected delay $delayMillis milliseconds, average=${totalDelay / delayCount} us, max: $maxDelay us") | |
} | |
coroutineScope { | |
launch { | |
delayLoop(5, 1000) | |
} | |
launch { | |
delayLoop(15, 1000) | |
} | |
launch { | |
delayLoop(50, 1000) | |
} | |
launch { | |
delayLoop(500, 100) | |
} | |
} | |
} | |
/* | |
output on Linux 6.5.5 + JDK 17 + Kotlin 1.9.0 + coroutines 1.6.4 | |
Expected delay 5 milliseconds, average=5172 us, max: 6948 us | |
Expected delay 15 milliseconds, average=15179 us, max: 16478 us | |
Expected delay 500 milliseconds, average=500219 us, max: 501024 us | |
Expected delay 50 milliseconds, average=50224 us, max: 51301 us | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment