You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin协程中measureTimeMillis计时结果异常原因咨询

Kotlin协程计时异常问题解析

核心问题:measureTimeMillis没等协程执行完

你第一个代码的问题出在**measureTimeMillis的作用范围和协程作用域的等待逻辑**上:

  • launch是非阻塞式的:你用measureTimeMillis包裹的只是「启动两个协程」的操作,启动协程本身是瞬间完成的,所以time变量记录的根本不是两个doXX函数的执行时间,而是启动协程的耗时(通常只有几毫秒)。
  • 你看到的“3秒”是程序总运行时间,不是measureTimeMillis的结果:runBlocking作用域会阻塞当前线程,直到它所有直接子协程都执行完。你第三个launch里的delay(你说打印3秒,应该是实际测试时设置为3秒)让整个程序等待3秒才结束,但time变量的值其实很小——你打印的time和你感知的程序运行时间完全是两回事。

为什么第二个代码能正确计时?

第二个代码里用了coroutineScope,这是Kotlin结构化并发的核心作用域之一:

  • coroutineScope会挂起当前协程,直到它所有子协程全部执行完毕
  • 两个launch放在coroutineScope里,doWorld函数会等这两个协程都跑完才返回,所以measureTimeMillis包裹的doWorld就能准确记录两个协程并发执行的总耗时(约2秒)。

修正第一个代码的两种常用方式

方法1:用coroutineScope包裹两个launch

fun main() = runBlocking<Unit> {
    val time = measureTimeMillis {
        coroutineScope {
            launch { doSomethingUsefulOne() }
            launch { doSomethingUsefulTwo() }
        }
    }
    println("Completed in $time ms") // 约1000ms,两个协程并发执行
}

suspend fun doSomethingUsefulOne() {
    delay(1000L)
}

suspend fun doSomethingUsefulTwo() {
    delay(1000L)
}

方法2:用async+await等待协程结果

fun main() = runBlocking<Unit> {
    val time = measureTimeMillis {
        val job1 = async { doSomethingUsefulOne() }
        val job2 = async { doSomethingUsefulTwo() }
        job1.await()
        job2.await()
    }
    println("Completed in $time ms") // 约1000ms
}

suspend fun doSomethingUsefulOne() {
    delay(1000L)
}

suspend fun doSomethingUsefulTwo() {
    delay(1000L)
}

内容的提问来源于stack exchange,提问作者ntos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:41:30