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()
相关推荐
懒人村杂货铺19 分钟前
Android BLE 扫描完整实战
android
TeleostNaCl3 小时前
如何安装 Google 通用的驱动以便使用 ADB 和 Fastboot 调试(Bootloader)设备
android·经验分享·adb·android studio·android-studio·android runtime
fatiaozhang95273 小时前
中国移动浪潮云电脑CD1000-系统全分区备份包-可瑞芯微工具刷机-可救砖
android·网络·电脑·电视盒子·刷机固件·机顶盒刷机
2501_915918414 小时前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
lichong9514 小时前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之dist打包发布在Android工程asserts里
android·vue.js·iphone
Android出海4 小时前
Android 15重磅升级:16KB内存页机制详解与适配指南
android·人工智能·新媒体运营·产品运营·内容运营
一只修仙的猿4 小时前
毕业三年后,我离职了
android·面试
编程乐学5 小时前
安卓非原创--基于Android Studio 实现的新闻App
android·ide·android studio·移动端开发·安卓大作业·新闻app
雅雅姐6 小时前
Android14 init.rc中on boot阶段操作4
android
fatiaozhang95277 小时前
中国移动中兴云电脑W132D-RK3528-2+32G-刷机固件包(非原机制作)
android·xml·电脑·电视盒子·刷机固件·机顶盒刷机