我正在学习协同,我遇到了以下令人惊讶的行为(对我来说)。我想要一张平行地图。我认为有4种解决办法:
map,没有并行性pmap,来自这里。coroutineScope并使用了GlobalScope。parallelStream守则:
import kotlinx.coroutines.*
import kotlin.streams.toList
import kotlin.system.measureNanoTime
inline fun printTime(msg: String, f: () -> Unit) =
println("${msg.padEnd(15)} time: ${measureNanoTime(f) / 1e9}")
suspend fun <T, U> List<T>.pmap(f: (T) -> U) = coroutineScope {
map { async { f(it) } }.map { it.await() }
}
suspend fun <T, U> List<T>.pmapGlob(f: (T) -> U) =
map { GlobalScope.async { f(it) } }.map { it.await() }
fun eval(i: Int) = (0 .. i).sumBy { it * it }
fun main() = runBlocking {
val list = (0..200).map { it * it * it }
printTime("No parallelism") { println(list.map(::eval).sum()) }
printTime("CoroutineScope") { println(list.pmap(::eval).sum()) }
printTime("GlobalScope") { println(list.pmapGlob(::eval).sum()) }
printTime("ParallelStream") { println(list.parallelStream().map(::eval).toList().sum()) }
}产出(不包括总数):
No parallelism time: 0.85726849
CoroutineScope time: 0.827426385
GlobalScope time: 0.145788785
ParallelStream time: 0.161423263正如您所看到的,在coroutineScope中几乎没有增益,而对于GlobalScope,它的工作速度与parallelStream一样快。原因何在?我能有一个解决方案,它具有coroutineScope的所有优点,具有相同的速度增益吗?
发布于 2019-04-05 09:02:54
范围只是间接地涉及到您所观察到的差异。
GlobalScope是一个单例,它定义了自己的调度程序,即Dispatchers.Default。它由线程池支持。
coroutineScope没有定义自己的dispatcher,因此您可以从调用方继承它,在本例中是由runBlocking创建的。它使用调用的单个线程。
如果您将coroutineScope替换为withContext(Dispatchers.Default),您将得到相同的时间。实际上,您应该这样写这个(而不是GlobalScope),以便在一些并发任务可能失败的情况下获得正常的行为。
https://stackoverflow.com/questions/55531464
复制相似问题