Skip to content

Instantly share code, notes, and snippets.

@vihangpatil
Created June 3, 2020 13:11
Show Gist options
  • Save vihangpatil/9274a5feed139551b6887b22cf876935 to your computer and use it in GitHub Desktop.
Save vihangpatil/9274a5feed139551b6887b22cf876935 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.jupiter.api.Test
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class DispatcherTest {
@Test
@ExperimentalTime
fun testDefaultDispatcher() = runBlocking {
val duration = measureTime {
withContext(Dispatchers.Default) {
repeat(times) {
launch {
blockingIOOperation()
}
}
}
}
println("Time taken by Dispatchers.Default: $duration")
}
@Test
@ExperimentalTime
fun testIODispatcher() = runBlocking {
val duration = measureTime {
withContext(Dispatchers.IO) {
repeat(times) {
launch {
blockingIOOperation()
}
}
}
}
println("Time taken by Dispatchers.IO: $duration")
}
/**
* This represents non-Kotlin blocking code.
*/
private fun blockingIOOperation() {
Thread.sleep(sleep)
}
companion object {
const val times = 128
const val sleep = 1000L
}
}
@vihangpatil
Copy link
Author

On a 8-core hyperthreaded CPU, the Dispatchers.Default has 16 threads.
Dispatchers.IO has 64 threads.

For times value > 64 and of the order of 2, Default dispatcher takes 4 times (64/16) the duration of IO dispatcher to execute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment