Kotlin:协程 VS 传统线程

结论

JVM平台,Kotlin语言使用多协程处理任务的效率并不优于传统多线程处理任务的效率。

背景

协程的概念很早就提出来了,先后已经被Go、Python等多个语言所支持。作为Android的第一开发语言,Kotlin官方也宣布支持了协程。但Kotlin的协程处理任务的效率真的高于传统多线程吗?

方案

模拟一堆任务,分别使用Kotlin多线程和Kotlin多协程并发处理这些任务,统计各自处理完成所有任务消耗的总时间,作为衡量效率高低的依据。本文的具体验证方案如下:

任务模拟:for循环中重复执行除法运算10G次作为一个任务

任务量模拟:20个模拟任务

多线程实现:ThreadPoolExecutor + Callable + CountDownLatch,其中线程池的核心线程数为当前硬件处理器最大核心数+1个,使用Callable是为了方便返回每一个任务具体耗时,而CountDownLatch则是为了监控是否所有的任务都已执行完成。

多协程实现:GlobalScope + Callable + CountDownLatch,使用默认的Scope开启协程,此处使用Callable只是为了方便统一两个测试环境的数据源可以公用,而单纯地在协程中调用了Callable的call()方法,CountDownLatch作用和多线程实现中的作用一致。

实施

硬件环境:

软件环境:

IDEA:

JDK:

结果统计

数据分析

从上述数据可以看出Kotlin的多协程在执行任务过程的效率并没有传统多线程优秀,反而还有一点下降。从操作系统层面来讲,协程确实是可以通过减少线程切换、上下文切换来提高效率,而试验数据却并不是预期的结果。这不得不让人怀疑Kotlin的底层是否真的就实现了协程,还是说仅仅只是基于线程的封装,类似于RxJava那种。

其他

以上仅为个人理解,如有不足之处请谅解,您也可以留言指出。

完整代码:

添加依赖: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

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值