Kotlin parallel computation of large array

冷暖自知 提交于 2019-12-24 11:27:36

问题


I have a large array and need compute result based on each item of this array. My PC's processor has 2 cores. I have compared different ways to achieve parallel execution in Kotlin.

I wrote simple example to illustrate this. First way is Java parallel stream, second is plain Kotlin map, third is coroutine version of map.

fun p() = runBlocking {
    val num = (0 until 1_000_000).toList()
    println(measureTimeMillis {
        num.stream().parallel().map { it * 2 }.collect(Collectors.toList())
    })
    println(measureTimeMillis {
        num.map { it * 2 }
    })
    println(measureTimeMillis {
        num.pmap { it * 2 }
    })
}

suspend fun <A, B> Iterable<A>.pmap(f: suspend (A) -> B): List<B> = coroutineScope {
    map { async { f(it) } }.map { it.await() }
}

The output (in ms.):

152
64
1620

Why pmap version is so slow? How to improve the code?

来源:https://stackoverflow.com/questions/56491296/kotlin-parallel-computation-of-large-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!