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

Kotlin开发的Android应用中如何测量两个API调用的执行时长?

Kotlin Android 双API执行时长测算最优方案

最优方案采用Kotlin标准库原生计时API实现,无需引入额外依赖、不改动原有并发逻辑、侵入性极低,具体实现如下:


方案1:直接在async块内嵌入计时(单场景使用首选)

直接用Kotlin标准库的measureTimeMillis包裹单接口调用,精准统计每个接口的独立耗时,完全保留原有并行请求逻辑:

fun initialization() {
    viewModelScope.launch(Dispatchers.IO) {
        // 声明变量存储两个接口的耗时
        var configRefreshCost = 0L
        var categoryRefreshCost = 0L

        val configurationRefresh = async {
            // 统计configuration接口耗时
            configRefreshCost = measureTimeMillis {
                configurationRepository.refresh()
            }
        }
        val categoryRefresh = async {
            // 统计category接口耗时
            categoryRefreshCost = measureTimeMillis {
                categoryRepository.refresh()
            }
        }

        try {
            configurationRefresh.await()
            categoryRefresh.await()
            // 此处可按需执行耗时打印、埋点上报等逻辑
            Log.d("API_TIMING", "配置接口耗时:${configRefreshCost}ms")
            Log.d("API_TIMING", "分类接口耗时:${categoryRefreshCost}ms")
        } catch (e: Exception) {
            status.postValue(Status.ShowMaintenance)
            // 可选:异常场景也可上报对应接口耗时,辅助问题排查
        } finally {
            // 原有无关逻辑保留
            DO SOME IRELEVANT CODE
        }
    }
}

该方案优势:

  • 完全不改动原有并发逻辑,两个接口仍保持并行请求
  • 统计精度为单接口从发起调用到返回/报错的真实耗时
  • 不需要修改Repository层代码,侵入性极低
  • 标准库API性能开销可忽略不计

方案2:封装通用计时函数(多接口统计场景推荐)

如果后续有大量接口需要统计耗时,可封装通用高阶函数复用逻辑:

// 通用耗时统计工具,返回接口返回值+耗时
suspend fun <T> measureApiRun(block: suspend () -> T): Pair<T, Long> {
    val cost = measureTimeMillis {
        val result = block()
        return@measureApiRun result to cost
    }
}

调用示例:

fun initialization() {
    viewModelScope.launch(Dispatchers.IO) {
        val configurationRefresh = async {
            measureApiRun { configurationRepository.refresh() }
        }
        val categoryRefresh = async {
            measureApiRun { categoryRepository.refresh() }
        }

        try {
            val (_, configCost) = configurationRefresh.await()
            val (_, categoryCost) = categoryRefresh.await()
            Log.d("API_TIMING", "配置接口耗时:${configCost}ms")
            Log.d("API_TIMING", "分类接口耗时:${categoryCost}ms")
        } catch (e: Exception) {
            status.postValue(Status.ShowMaintenance)
        } finally {
            DO SOME IRELEVANT CODE
        }
    }
}

注意事项

  • 不要在两个await执行完后统一计时,那样只能拿到两个接口的总耗时,无法拆分单个接口的耗时
  • 如果需要统计异常场景的耗时,可将计时逻辑包裹在接口调用的try-catch内部,即可拿到从发起请求到报错的时长
  • 不推荐手动写System.currentTimeMillis()前后相减的逻辑,标准库measureTimeMillis已经做了封装,写法更简洁且不易出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:15:02