Android 中获取当前 CPU 频率和占用率

最近在优化 App 的性能,需要获取当前 CPU视频频率和占用率,通过查询资料,大致思路如下:

目前没有标准的 API 来获取 CPU 的使用频率,只能通过读取指定 CPU 文件获取当前 CPU 频率,在某些机器或者特定版本中,可能需要ROOT 权限或者特殊权限,因此会存在一定几率的失败,因此需要做好 Try...catch 动作。又因为现在手机 CPU 的多核数目,因此我们可能需要获取多个 CPU 频率数,并取平均值。

获取系统 CPU 核心数:

kotlin 复制代码
 val cpuCoreNum = Runtime.getRuntime().availableProcessors()

获取指定 CPU 当前频率:

kotlin 复制代码
/sys/devices/system/cpu/cpu${index}/cpufreq/scaling_cur_freq

那么核心代码为:

kotlin 复制代码
private fun getAllCpuCoreFrequency() : Long {

        var frequency = 0L

        for (index in 0 until  cpuCoreNum){
            frequency += readFile("/sys/devices/system/cpu/cpu$index/cpufreq/scaling_cur_freq")
        }

        BLog.d("frequency : $frequency")

        return frequency / cpuCoreNum
    }


  private fun readFile(filePath: String): Long{
        try {
            val file = RandomAccessFile(filePath, "r")
            val content = file.readLine()
            file.close()

            if (TextUtils.isEmpty(content)){
                return 0L
            }

            BLog.d("readFile content : $content")

            return content.trim().toLong()

        }catch (e : Exception){
            e.printStackTrace()

           return 0L
        }
    }

如果需要获取 CPU 的占用率,那么就需要知道每个核心的最大频率和最小频率,同样是通过文件获取:

kotlin 复制代码
//max frequency file
/sys/devices/system/cpu/cpu${index}/cpufreq/cpuinfo_max_freq

//min frequency file
/sys/devices/system/cpu/cpu${index}/cpufreq/cpuinfo_min_freq

那么核心代码为:

kotlin 复制代码
object CPUUtils {

    private var cpuCoreNum = 0
    private var cpuMaxFrequency = 0L
    private var cpuMinFrequency = 0L

    fun initCpuCoreNum(){
        if (cpuCoreNum <= 0 || cpuMaxFrequency <= 0L || cpuMinFrequency <= 0L){

            cpuCoreNum = Runtime.getRuntime().availableProcessors()
            initMaxAndMinFrequency()

            if (cpuCoreNum > 0 && cpuMaxFrequency > 0L && cpuMinFrequency > 0L){
               SpManager.getInstance().setCanUseCPUFrequency(true)
            }
        }

        BLog.d("cpuCoreNum : $cpuCoreNum")
    }

    private fun initMaxAndMinFrequency()  {
        if (cpuCoreNum <= 0){
            return
        }

        cpuMaxFrequency = 0L
        cpuMinFrequency = 0L

        for (index in 0 until cpuCoreNum){
            cpuMaxFrequency += readFile("/sys/devices/system/cpu/cpu${index}/cpufreq/cpuinfo_max_freq")
            cpuMinFrequency += readFile("/sys/devices/system/cpu/cpu${index}/cpufreq/cpuinfo_min_freq")
        }


        BLog.d("cpuMaxFrequency : $cpuMaxFrequency, cpuMinFrequency : $cpuMinFrequency")
    }


    private fun readFile(filePath: String): Long{
        try {
            val file = RandomAccessFile(filePath, "r")
            val content = file.readLine()
            file.close()

            if (TextUtils.isEmpty(content)){
                return 0L
            }

            BLog.d("readFile content : $content")

            return content.trim().toLong()

        }catch (e : Exception){
           ExceptionHandler.recordException(e)

           return 0L
        }
    }
    
    private fun getAllCpuCoreFrequency() : Long {
        initCpuCoreNum()

        if (cpuCoreNum <=0){
            return 0L
        }

        var frequency = 0L

        for (index in 0 until  cpuCoreNum){
            frequency += readFile("/sys/devices/system/cpu/cpu$index/cpufreq/scaling_cur_freq")
        }

        BLog.d("frequency : $frequency")

        return frequency
    }

    fun findCurrentFrequencyPercent() : Long {

        val currentFrequency = getAllCpuCoreFrequency()

        BLog.d("currentFrequency : $currentFrequency, cpuMinFrequency : $cpuMinFrequency, cpuMaxFrequency : $cpuMaxFrequency")

        if (cpuMaxFrequency - cpuMinFrequency <= 0L || currentFrequency - cpuMinFrequency < 0L || cpuMaxFrequency - currentFrequency < 0L){
            return 0L
        }

        return (currentFrequency - cpuMinFrequency) * 100 / (cpuMaxFrequency - cpuMinFrequency)
    }


    fun getCpuCoreFrequency() : Long {
        initCpuCoreNum()

        if (cpuCoreNum <=0){
            return 0L
        }

        return getAllCpuCoreFrequency() / cpuCoreNum
    }

}

获取 CPU 频率:

kotlin 复制代码
CPUUtils.getCpuCoreFrequency()

获取 CPU 占用率:

kotlin 复制代码
CPUtils.findCurrentFrequencyPercent()
相关推荐
鸿蒙布道师25 分钟前
鸿蒙NEXT开发设备相关工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
darkchink1 小时前
[LevelDB]Block系统内幕解析-元数据块(Meta Block)&元数据索引块(MetaIndex Block)&索引块(Index Block)
android·java·服务器·c语言·数据库·c++·分布式
archko2 小时前
telophoto源码查看记录 三
android
QING6182 小时前
Activity和Fragment生命周期 —— 新手指南
android·面试·app
QING6182 小时前
Kotlin Result 类型扩展详解 —— 新手使用指南
android·kotlin·app
缘来的精彩3 小时前
kotlin 多个fragment beginTransaction容器添加使用
android·开发语言·kotlin
安小牛3 小时前
Kotlin 学习-集合
android·开发语言·学习·kotlin
顾林海3 小时前
Flutter 图片组件全面解析:从基础加载到高级应用
android·前端·flutter
molong9313 小时前
Android开发鸿蒙环境问题记录
android·华为·harmonyos
顾林海3 小时前
深度解析LinkedHashSet工作原理
android·java·面试