結(jié)論
JVM平臺(tái),Kotlin語(yǔ)言使用多協(xié)程處理任務(wù)的效率并不優(yōu)于傳統(tǒng)多線程處理任務(wù)的效率。
背景
協(xié)程的概念很早就提出來(lái)了叽奥,先后已經(jīng)被Go俱两、Python等多個(gè)語(yǔ)言所支持饱狂。作為Android的第一開發(fā)語(yǔ)言,Kotlin官方也宣布支持了協(xié)程宪彩。但Kotlin的協(xié)程處理任務(wù)的效率真的高于傳統(tǒng)多線程嗎休讳?
方案
模擬一堆任務(wù),分別使用Kotlin多線程和Kotlin多協(xié)程并發(fā)處理這些任務(wù)尿孔,統(tǒng)計(jì)各自處理完成所有任務(wù)消耗的總時(shí)間俊柔,作為衡量效率高低的依據(jù)。本文的具體驗(yàn)證方案如下:
任務(wù)模擬:for循環(huán)中重復(fù)執(zhí)行除法運(yùn)算10G次作為一個(gè)任務(wù)
任務(wù)量模擬:20個(gè)模擬任務(wù)
多線程實(shí)現(xiàn):ThreadPoolExecutor + Callable + CountDownLatch活合,其中線程池的核心線程數(shù)為當(dāng)前硬件處理器最大核心數(shù)+1個(gè)雏婶,使用Callable是為了方便返回每一個(gè)任務(wù)具體耗時(shí),而CountDownLatch則是為了監(jiān)控是否所有的任務(wù)都已執(zhí)行完成白指。
多協(xié)程實(shí)現(xiàn):GlobalScope + Callable +?CountDownLatch留晚,使用默認(rèn)的Scope開啟協(xié)程,此處使用Callable只是為了方便統(tǒng)一兩個(gè)測(cè)試環(huán)境的數(shù)據(jù)源可以公用告嘲,而單純地在協(xié)程中調(diào)用了Callable的call()方法错维,CountDownLatch作用和多線程實(shí)現(xiàn)中的作用一致。
實(shí)施
硬件環(huán)境:
軟件環(huán)境:
IDEA:
JDK:
結(jié)果統(tǒng)計(jì)
數(shù)據(jù)分析
從上述數(shù)據(jù)可以看出Kotlin的多協(xié)程在執(zhí)行任務(wù)過(guò)程的效率并沒有傳統(tǒng)多線程優(yōu)秀橄唬,反而還有一點(diǎn)下降赋焕。從操作系統(tǒng)層面來(lái)講,協(xié)程確實(shí)是可以通過(guò)減少線程切換仰楚、上下文切換來(lái)提高效率隆判,而試驗(yàn)數(shù)據(jù)卻并不是預(yù)期的結(jié)果犬庇。這不得不讓人懷疑Kotlin的底層是否真的就實(shí)現(xiàn)了協(xié)程,還是說(shuō)僅僅只是基于線程的封裝蜜氨,類似于RxJava那種械筛。
其他
以上僅為個(gè)人理解,如有不足之處請(qǐng)諒解飒炎,您也可以留言指出埋哟。
完整代碼:
添加依賴:implementation"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1"
package com.xxxx
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.Future
fun main() {
Compare().startCompare()
}
class Compare {
private val timeCostMap =mutableMapOf()
fun startCompare() {
testThread()
println("===============================================================================")
Thread.sleep(3000)
testCoroutine()
println("===============================================================================")
var threadTotal =0L
? ? ? ? var coroutineTotal =0L
? ? ? ? timeCostMap.forEach{ t, u->
? ? ? ? ? ? println("$t cost: $u")
if (t.startsWith("Thread")) {
threadTotal += u
}else {
coroutineTotal += u
}
}
? ? ? ? println("Execute $CYCLE_TIME tasks, thread cost: ${threadTotal *1.0 /1000} seconds, coroutine cost: ${coroutineTotal *1.0 /1000} seconds")
}
private fun testThread() {
// init
? ? ? ? val startTime = System.currentTimeMillis()
val countDownLatch = CountDownLatch(CYCLE_TIME)
val maximumOfThread = Runtime.getRuntime().availableProcessors() +1
? ? ? ? val threadPools = Executors.newFixedThreadPool(maximumOfThread){ r-> Thread(r)}
? ? ? ? val resultList =mutableListOf>()
val tasks = getTasks(countDownLatch)
val size = tasks.size
? ? ? ? val initializedTime = System.currentTimeMillis()
println("[Thread]---->? initialized cost: ${initializedTime - startTime}毫秒")
// execute
? ? ? ? for (indexin 0 until size) {
resultList.add(threadPools.submit(tasks[index]))
}
val tasksSubmittedTime = System.currentTimeMillis()
println("[Thread]---->? submit tasks cost: ${tasksSubmittedTime - initializedTime}毫秒")
// check if all task finished
? ? ? ? countDownLatch.await()
val tasksFinishedTime = System.currentTimeMillis()
println("[Thread]---->? execute tasks cost: ${tasksFinishedTime - tasksSubmittedTime}毫秒")
// count time cost
? ? ? ? for (indexin 0 until resultList.size) {
val future = resultList[index]
timeCostMap["Thread: task $index"] = future.get()
}
// all done
? ? }
private fun testCoroutine() {
// init
? ? ? ? val startTime = System.currentTimeMillis()
val countDownLatch = CountDownLatch(CYCLE_TIME)
val tasks = getTasks(countDownLatch)
val size = tasks.size
? ? ? ? val initializedTime = System.currentTimeMillis()
println("[Coroutine]---->? initialized cost: ${initializedTime - startTime}毫秒")
// execute
? ? ? ? for (indexin 0 until size) {
GlobalScope.launch {
? ? ? ? ? ? ? ? val costTime = tasks[index].call()
timeCostMap["Coroutine: task $index"] = costTime
}
? ? ? ? }
val tasksSubmittedTime = System.currentTimeMillis()
println("[Coroutine]---->? submit tasks cost: ${tasksSubmittedTime - initializedTime}毫秒")
// check if all task finished
? ? ? ? countDownLatch.await()
val tasksFinishedTime = System.currentTimeMillis()
println("[Coroutine]---->? execute tasks cost: ${tasksFinishedTime - tasksSubmittedTime}毫秒")
// all done
? ? }
private fun getTasks(countDownLatch: CountDownLatch): MutableList {
val tasks =mutableListOf()
for (indexin 0 until CYCLE_TIME) {
tasks.add(Task(countDownLatch))
}
return tasks
}
inner class Task(private val countDownLatch: CountDownLatch) : Callable {
private fun taskLogics(): Long {
val startTIme = System.currentTimeMillis()
for (countin 0 until 10) {
for (startin 0 until _G) {
val i = System.currentTimeMillis() /3
? ? ? ? ? ? ? ? }
}
countDownLatch.countDown()
return System.currentTimeMillis() - startTIme
}
override fun call(): Long {
return taskLogics()
}
}
companion object {
const val _BYTE =1
? ? ? ? const val _K =1024 *_BYTE
? ? ? ? const val _M =1024 *_K
? ? ? ? const val _G =1024 *_M
? ? ? ? const val CYCLE_TIME =20
? ? }
}