如何获取android上每个cpu核心的使用情况

2023-12-10

我在 Android 上开发了一个小部件,它显示许多有用的信息。

我正在尝试修改此方法以返回一个 cpu 核心的使用百分比,以便获得每个核心的使用百分比!

在我的 HTC One X 上,我在“ /proc/stat ”中有:

cpu  183549 10728 236016 3754379 7530 41 1013 0 0 0
cpu0 141962 5990 196956 720894 3333 41 970 0 0 0
cpu1 23400 2550 23158 980901 2211 0 23 0 0 0
cpu2 13602 1637 12561 1019126 1216 0 18 0 0 0
cpu3 4585 551 3341 1033458 770 0 2 0 0 0

我使用此方法返回所有 cpu 核心的使用百分比。

public float readUsage() {
    try {

        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();


        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(800);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" ");

        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

我正在尝试使用 cpu1,但它不起作用:

public float readUsageCPU0() {
    try {

        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        reader.seek(0);
        String load = reader.readLine();
        load = reader.readLine();
        load = reader.readLine();


        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(500);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        load = reader.readLine();
        load = reader.readLine();
        reader.close();

        toks = load.split(" ");

        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
}

这允许读取一行并且光标停留在该行的末尾:

String load = reader.readLine();

因此,我尝试使用它两次以获得 CPU0 的使用权,第三次尝试使用它来获得 CPU1 的使用权。 但结果总是0或100...我不明白!

我使用的方法正确吗? 我使用的文件正确吗? 这个结果正常吗?

请帮忙 !!!


public class CpuStat {
    private static final String TAG = "CpuUsage";
    private RandomAccessFile statFile;
    private CpuInfo mCpuInfoTotal;
    private ArrayList<CpuInfo> mCpuInfoList;

    public CpuStat() {
    }

    public void update() {
        try {           
            createFile();
            parseFile();
            closeFile();
        } catch (FileNotFoundException e) {
            statFile = null;
            Log.e(TAG, "cannot open /proc/stat: " + e);
        } catch (IOException e) {
            Log.e(TAG, "cannot close /proc/stat: " + e);
        }
    }

    private void createFile() throws FileNotFoundException {
        statFile = new RandomAccessFile("/proc/stat", "r");
    }

    public void closeFile() throws IOException {
        if (statFile != null)
            statFile.close();
    }

    private void parseFile() {
        if (statFile != null) {
            try {
                statFile.seek(0);
                String cpuLine = "";
                int cpuId = -1;
                do { 
                    cpuLine = statFile.readLine();
                    parseCpuLine(cpuId, cpuLine);
                    cpuId++;
                } while (cpuLine != null);
            } catch (IOException e) {
                Log.e(TAG, "Ops: " + e);
            }
        }
    }

    private void parseCpuLine(int cpuId, String cpuLine) {
        if (cpuLine != null && cpuLine.length() > 0) { 
            String[] parts = cpuLine.split("[ ]+");
            String cpuLabel = "cpu";
            if ( parts[0].indexOf(cpuLabel) != -1) {
                createCpuInfo(cpuId, parts);
            }
        } else {
            Log.e(TAG, "unable to get cpu line");
        }
    }

    private void createCpuInfo(int cpuId, String[] parts) {
        if (cpuId == -1) {                      
            if (mCpuInfoTotal == null)
                mCpuInfoTotal = new CpuInfo();
            mCpuInfoTotal.update(parts);
        } else {
            if (mCpuInfoList == null)
                mCpuInfoList = new ArrayList<CpuInfo>();
            if (cpuId < mCpuInfoList.size())
                mCpuInfoList.get(cpuId).update(parts);
            else {
                CpuInfo info = new CpuInfo();
                info.update(parts);
                mCpuInfoList.add(info);
            }                               
        }
    }

    public int getCpuUsage(int cpuId) {
        update();
        int usage = 0;
        if (mCpuInfoList != null) {
            int cpuCount = mCpuInfoList.size();
            if (cpuCount > 0) {
                cpuCount--;
                if (cpuId == cpuCount) { // -1 total cpu usage
                    usage = mCpuInfoList.get(0).getUsage(); 
                } else {
                    if (cpuId <= cpuCount)
                        usage = mCpuInfoList.get(cpuId).getUsage();
                    else
                        usage = -1;
                }
            }
        }
        return usage;
    }


    public int getTotalCpuUsage() {
        update();           
        int usage = 0;
        if (mCpuInfoTotal != null)
            usage = mCpuInfoTotal.getUsage();
        return usage;
    }


    public String toString() {
        update();
        StringBuffer buf = new StringBuffer();
        if (mCpuInfoTotal != null) {
            buf.append("Cpu Total : ");
            buf.append(mCpuInfoTotal.getUsage());
            buf.append("%");
        }   
        if (mCpuInfoList != null) {
            for (int i=0; i < mCpuInfoList.size(); i++) {
                CpuInfo info = mCpuInfoList.get(i); 
                buf.append(" Cpu Core(" + i + ") : ");
                buf.append(info.getUsage());
                buf.append("%");
                info.getUsage();
            }
        }           
        return buf.toString();
    }

    public class CpuInfo {
        private int  mUsage;            
        private long mLastTotal;
        private long mLastIdle;

        public CpuInfo() {
            mUsage = 0;
            mLastTotal = 0;
            mLastIdle = 0;  
        }

        private int  getUsage() {
            return mUsage;
        }

        public void update(String[] parts) {
            // the columns are:
            //
            //      0 "cpu": the string "cpu" that identifies the line
            //      1 user: normal processes executing in user mode
            //      2 nice: niced processes executing in user mode
            //      3 system: processes executing in kernel mode
            //      4 idle: twiddling thumbs
            //      5 iowait: waiting for I/O to complete
            //      6 irq: servicing interrupts
            //      7 softirq: servicing softirqs
            //
            long idle = Long.parseLong(parts[4], 10);
            long total = 0;
            boolean head = true;
            for (String part : parts) {
                if (head) {
                    head = false;
                    continue;
                }
                total += Long.parseLong(part, 10);
            }
            long diffIdle   =   idle - mLastIdle;
            long diffTotal  =   total - mLastTotal;
            mUsage = (int)((float)(diffTotal - diffIdle) / diffTotal * 100);
            mLastTotal = total;
            mLastIdle = idle;
            Log.i(TAG, "CPU total=" + total + "; idle=" + idle + "; usage=" + mUsage);
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取android上每个cpu核心的使用情况 的相关文章

  • 如何在android中实现触摸平滑图像橡皮擦?

    我已经从 API 演示中看到了finturePaint java 我想实现触摸平滑橡皮擦 通过在android中触摸移动来擦除部分图像 FingerPaint 告诉我要实现这个 mPaint setXfermode new PorterDu
  • gradle更新后无法找到方法(无法编译项目)

    我尝试将项目中的 gradle 版本更新为 4 1 milestone 1 以下这些说明 https developer android com studio build gradle plugin 3 0 0 migration html
  • Android Studio:XML 布局中的“包装在容器中”

    编辑 XML 布局文件时 Eclipse 有一项称为 包裹在容器中 的功能 重新格式化 gt Android gt 可让您选择一个或多个视图并在其周围包裹您选择的布局 Android Studio中有类似的东西吗 目前正在实施中 问题 69
  • AdapterContextMenuInfo 始终为 null

    我尝试通过 android 开发文档中的书来做到这一点 this didn t create a menu i don t know why registerForContextMenu getListView setListAdapter
  • 如何正确释放Android MediaPlayer

    我正在尝试向我的 Android 应用程序添加一个按钮 当点击该按钮时它会播放 MP3 我已经让它工作了 但没有办法释放 mediaPlayer 对象 因此即使在我离开活动后它仍然会继续播放 如果我在react 方法之外初始化MediaPl
  • Android WebView里面的ScrollView只滚动scrollview

    在我的应用程序中 我有一个 ScrollView 其中包含一些线性视图 一些文本视图和一个 Webview 然后是其他线性布局等 问题是 WebView 不滚动 Scroll 仅侦听 ScrollView 有什么建议么
  • 自定义首选项中的android首选项水平分隔线?

    我创建了自己的自定义首选项对象来扩展首选项 我创建它们只是因为这些自定义数据类型没有首选项 一切正常 但我的自定义首选项没有相同的外观 因为它们缺少系统首选项对象具有的水平分隔线 我已经查找了创建水平分隔线的代码 但我找不到它是在哪里完成的
  • 如何更改终端的默认目录?

    我想更改 Android Studio v2 2 2 终端的默认目录 当我打开终端时 它基于项目的目录 C 项目路径 我经常需要使用adb shell 所以我必须导航到 SDK 路径 平台工具 才能使用 adb 命令 是否可以更改终端的默认
  • Dialog.setTitle 不显示标题

    我正在尝试向我的对话框添加自定义标题 但是每当我运行我的应用程序时 它都不会显示标题 我创建对话框的代码是 final Dialog passwordDialog new Dialog this passwordDialog setCont
  • Android 深度链接至 Instagram 应用

    Instagram 已经发布了 iOS 深层链接的 url 方案 但尚未为 Android 创建文档 有没有办法深入链接到 Android 上的 Instagram 应用程序 以转到 Instagram 应用程序中的特定位置 例如 Inst
  • Android:后台Activity可以执行代码吗?

    后台的活动是否被视为 正在运行 并且可以执行代码 还是处于挂起状态 他们暂停了 活动生命周期 http developer android com reference android app Activity html ActivityLi
  • 我应该释放或重置 MediaPlayer 吗?

    我有自己的自定义适配器类 称为 WordAdapter 并且我正在使用媒体播放器 名为pronounce WordAdapter 类中的全局变量 我有不同的活动 其中每个列表项都有线性布局 名为linearLayout 我正在设置onCli
  • 上网本上可以进行Android开发吗? [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我想使用我的上网本进行 Android 开发 但是当我尝试使用 Eclipse 运行 SDK 时 没有加载任何内容 上网本对于 Android 开发来
  • 卡片视图 单击卡片移至新活动

    我是 Android 编程新手 正在研究卡片布局 我想知道如何使其可点击 android clickable true android foreground android attr selectableItemBackground 我的卡
  • Android - 以编程方式选择菜单选项

    有没有办法以编程方式选择菜单选项 基本上 我希望视图中的按钮能够执行与按特定菜单选项相同的操作 我正在考虑尝试调用 onOptionsItemSelected MenuItem item 但我不知道要为菜单项添加什么 是的 有一种方法可以选
  • 没有用于警告的设置器/字段 Firebase 数据库检索数据填充列表视图

    我只是想将 Firebase 数据库中的数据填充到我的列表视图中 日志显示正在检索数据 但适配器不会将值设置为列表中单个列表项中的文本 它只说 没有二传手 场地插入值 这让我觉得我的设置器没有正确制作 但 Android Studio 自动
  • 问题:为什么React Native Video不能全屏播放视频?

    我正在react native 0 57 7 中为android和ios创建一个应用程序并使用反应本机视频 https github com react native community react native video播放上传到的视频
  • Android:如何从网络异步获取搜索建议?

    我创建了一个可搜索的活动 现在 我想添加从网络服务获取的搜索建议 我想异步获取这些建议 根据添加自定义建议 http developer android com guide topics search adding custom sugge
  • 我的应用程序中的后退按钮出现问题[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我想在手机关闭时清除共享首选项值 你
  • 发布的 Android apk 出现错误“包文件未正确签名”

    我最近将我的应用程序上传到 Android 市场 但是由于错误 下载时它拒绝运行 包文件未正确签名 我首先使用 eclipse 发布了数据包 右键单击导出 创建密钥库然后发布 但它拒绝工作 然后我下载了 keytool 和 jarsigne

随机推荐

  • Firebase Crashlytics Android NDK:崩溃报告上的空符号

    我在 Android Studio 中有一个项目 其中包含通过 JNI 调用使用一些本机库的 Android Java 服务 基本上 我有两个编译的库和另一个预编译的库 所以我无法访问源代码 由于预编译库仅为armeabi v7a 构建 因
  • 警告:mysqli_error() 需要 1 个参数,0 个给出错误

    我收到以下错误 警告 mysqli error 需要 1 个参数 给定 0 个参数 问题出在这行代码上 query mysqli query myConnection sqlCommand or die mysqli error 整个代码是
  • Android:使用 ACTION 视图打开图像的 URI

    这是代码 protected static final String DIR IMAGE data data it android myprogram images Intent intent new Intent intent setAc
  • TTFB(首字节时间)计算由什么组成,以及如何查看各个组件的时序?

    我看到 chrome 开发工具中报告的网络请求的首字节时间数字很高 我想改进它 但我不确定请求过程的哪一部分导致速度慢 一些来源将此测量引用为 DNS SSL 连接 发送 接收 等待 TTFB的权威定义是什么 如何准确衡量它的各个部分 使用
  • 设置新配置后如何更新所有 spring 对象?

    怎么刷新之前的 Autowired动态配置更改后的 spring 对象 Here is my updateConfig method GenericApplicationContext context new GenericApplicat
  • 为什么在 C/C++ 中交织 switch/for/if 语句是有效的? [复制]

    这个问题在这里已经有答案了 我正在阅读boost asio coroutine hpp并且无法理解BOOST ASIO CORO REENTER和BOOST ASIO CORO YIELD的实现 的扩展形式为 reenter this yi
  • 在您自己的软件中使用 VBA

    我想在我的软件中使用 Visual Basic 我想知道它是否受版权保护 任何线索将不胜感激 谢谢 VBScript 很容易嵌入 VBA 需要许可证 这是添加 VBScript 作为宏语言的 VB6 VBA 代码 With ScriptCo
  • 如何从 vmware_guest_disk_facts 获取字典条目

    我正在尝试获取特定硬盘的数据存储名称 但我未能成功地找出列表中的选择条目 此输出来自 ansible 模块 vmware guest disk facts 我将此输出保存到名为 vm info 的变量中 guest disk facts 0
  • java.lang.Throwable:setStateLocked

    每次从其他 Activity 意图到 LoginActivity 时 都会使应用程序崩溃 错误的Logcat AccessibilityManager setStateLocked wasEnabled false mIsEnabled 假
  • 将文本字符串转换为电子表格中的公式

    我正在尝试开发一个交互式电子表格 为预算文件创建叙述 将会有多种选择 一旦用户选择了一个项目 它将帮助他们计算总数 我想设置它们填写的选项框 例如 将允许输入 B1 B4 四个单元格 我将为四个单元格分别命名 即 A B C D 在参考文档
  • 将整数数组映射到嵌套数组访问

    有没有一种方法可以使用本身存储在数组中的索引来动态访问嵌套数组 主数组 矩阵嵌套可以是可变的 例如2 4 100 Example my array 1 2 3 4 5 6 7 8 9 10 11 12 my array access usi
  • LESS 无声多行注释

    有没有办法创建silentLESS 中的多行注释 我想要与 comment 相同的行为 但对于多行字符串 正如 harry 已经明确指出的 x and clean css选项也会删除评论 从版本 2 开始 clean css 选项已移至插件
  • 如何在 JavaScript 中使用 toLocaleString() 和 tofixed(2)

    我怎样才能在 JavaScript 中做到这一点 var num 2046430 num toLocaleString will give you 2 046 430 我尝试过的是 var num 2046430 num toLocaleS
  • 带有 MAX(n.property) 的 Cypher 返回节点

    With Cypher 我试图返回得分最高的节点 然而 它要么只返回分数 而没有任何 id 到节点 我需要在查询中添加什么 start n node WHERE HAS n score return MAX n score 该解决方案应该为
  • 找不到 Oracle jdbc 驱动程序

    我对 java 和数据库连接很陌生 我正在尝试与 Oracle 数据库建立一个非常简单的连接 当我运行这段代码时 import java sql import oracle jdbc pool OracleDataSource public
  • Nodejs 上的 Javascript ES6:类型错误:对象不是构造函数

    我有这个样本班sync js作为我项目中某处的模块 use strict export default class Sync constructor dbConnection this dbConnection dbConnection t
  • jquery validator - 仅验证可见元素

    我有一个隐藏 显示 div 的单选按钮 所有可见元素都是 必需的 但是在验证规则之后添加ignore hidden 不起作用 这是代码
  • 将序列划分为唯一对的集合

    我需要一个 of 函数 它可以将序列分成对 然后将它们组合起来 以便组合中的所有元素都是唯一的 我已经尝试了多种使用 python 的 itertools 的方法 但还没有找到解决方案 为了说明这一点 我想要一个采用以下序列的函数 1 2
  • 使用 UserDefaults 保存图像数组

    我有一个应用程序 用户可以在其中拍照 拍照后应将其保存到UserDefaults 我不断收到此错误 cannot invoke setObject with an argument list of type UIImage type for
  • 如何获取android上每个cpu核心的使用情况

    我在 Android 上开发了一个小部件 它显示许多有用的信息 我正在尝试修改此方法以返回一个 cpu 核心的使用百分比 以便获得每个核心的使用百分比 在我的 HTC One X 上 我在 proc stat 中有 cpu 183549 1