Created
June 3, 2020 13:11
-
-
Save vihangpatil/9274a5feed139551b6887b22cf876935 to your computer and use it in GitHub Desktop.
This file contains 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.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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.