大数组的Kotlin并行计算

时间:2019-06-07 09:08:26

标签: java multithreading kotlin kotlin-coroutines

我有一个大数组,需要根据此数组的每个项目计算结果。我的电脑的处理器有2个核心。 我比较了在Kotlin中实现并行执行的不同方法。

我写了一个简单的例子来说明这一点。第一种方法是Java并行流,第二种是普通的Kotlin地图,第三种是协程版本的地图。

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() }
}

输出(以毫秒为单位):

152
64
1620

为什么pmap版本这么慢?如何改进代码?

0 个答案:

没有答案