在我公司用Kotlin编写的android应用程序中,我有2个Api调用,我想测量它们的执行时间。
代码如下:
fun initialization() {
viewModelScope.launch(Dispatchers.IO) {
val configurationRefresh = async { configurationRepository.refresh() }
val categoryRefresh = async { categoryRepository.refresh() }
try {
configurationRefresh.await()
categoryRefresh.await()
} catch (e: Exception) {
status.postValue(Status.ShowMaintenance)
} finally {
DO SOME IRELEVANT CODE
}
}
}
}
我想测量configurationRepository.refresh()和categoryRepository.refresh() API调用的执行时间。执行此操作的最佳方法是什么?由于我认为这可以帮助人们,所以我会写。我发现对我来说最简单的解决方案是在kotlin中使用measureTimeMillis()函数。它是这样的:
viewModelScope.launch(Dispatchers.IO) {
val time = measureTimeMillis {
categoryRepository.refresh() //Api call
}
Log.println(Log.VERBOSE, "Api time testing", "$time")
}
日志中写入的时间是API调用的执行时间。