Skip to content

Instantly share code, notes, and snippets.

@Pooh3Mobi
Last active February 11, 2019 02:43
Show Gist options
  • Save Pooh3Mobi/78fee64207c939bc324e31378b46c54d to your computer and use it in GitHub Desktop.
Save Pooh3Mobi/78fee64207c939bc324e31378b46c54d to your computer and use it in GitHub Desktop.
Kotlin Parallel performance examples.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
main()
}
}
}
fun main() {
Thread {
log("many thread start")
measureTimeMillis {
manyTask1(400)
// manyTask2(400)
// manyTask3(400)
// manyTask4(400)
// manyTask5(400)
// manyTask6(400)
}.also {
log("[cost]: ${it}")
}
}.start()
}
fun manyTask1(num: Int) {
val latch = CountDownLatch(num)
(0..num).forEach { _ ->
Thread {
TimeUnit.MILLISECONDS.sleep(100)
latch.countDown()
}.start()
}
latch.await()
}
fun manyTask2(num: Int) {
val latch = CountDownLatch(num)
val executor = Executors.newScheduledThreadPool(4)
(0..num).forEach { _ ->
executor.execute {
TimeUnit.MILLISECONDS.sleep(100)
latch.countDown()
}
}
latch.await()
}
fun manyTask3(num: Int) {
val latch = CountDownLatch(num)
val executor = AsyncTask.THREAD_POOL_EXECUTOR
(0..num).forEach { _ ->
executor.execute {
TimeUnit.MILLISECONDS.sleep(100)
latch.countDown()
}
}
latch.await()
}
fun manyTask4(num: Int) {
runBlocking {
(0..num).toList().map {
suspend {
delay(100)
}
}.forEach {
launch(Dispatchers.Unconfined) {
withContext(IO) { it() }
}
}
}
}
fun manyTask6(num: Int) {
runBlocking {
(0..num).toList().map {
suspend {
delay(100)
}
}.forEach {
launch(Dispatchers.Default) {
withContext(IO) { it() }
}
}
}
}
fun manyTask5(num: Int) {
runBlocking {
(0..num).map {
async(IO) {
suspend {
delay(100)
}()
}
}.awaitAll()
}
}
fun log(msg: String) {
println("[ababab] $msg")
// Log.d("ababab", msg)
}
@Pooh3Mobi
Copy link
Author

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies {
    // async// kotlin coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
}

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