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()
相关推荐
还是奇怪3 小时前
Linux - 安全排查 3
android·linux·安全
Android采码蜂3 小时前
BLASTBufferQueue03-BufferQueueConsumer核心操作
android
Android采码蜂3 小时前
BLASTBufferQueue02-BufferQueueProducer核心操作
android
2501_915921434 小时前
没有Mac如何完成iOS 上架:iOS App 上架App Store流程
android·ios·小程序·https·uni-app·iphone·webview
码农明明4 小时前
Google Play 应用上架二三事
android·google
红橙Darren7 小时前
手写操作系统 - 环境搭建
android·微信·操作系统
_一条咸鱼_7 小时前
Android Runtime直接内存管理原理深度剖析(73)
android·面试·android jetpack
你听得到117 小时前
揭秘Flutter图片编辑器核心技术:从状态驱动架构到高保真图像处理
android·前端·flutter
wilinz7 小时前
Flutter Android 端接入百度地图踩坑记录
android·flutter
小袁拒绝摆烂10 小时前
SQL开窗函数
android·sql·性能优化