如何获得在Android上的每个CPU核心的使用 [英] How to get usage of each cpu core on android

查看:155
本文介绍了如何获得在Android上的每个CPU核心的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发在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核心的百分比。

 公众持股量readUsage(){
    尝试 {

        RandomAccessFile的读者=新RandomAccessFile的(的/ proc / STAT,R);
        字符串负荷= reader.readLine();


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

        长IDLE1 =的Long.parseLong(toks [5]);
        长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]);

        尝试 {
            视频下载(800);
        }赶上(例外五){}

        reader.seek(0);
        负载= reader.readLine();
        reader.close();

        toks = load.split();

        长IDLE2 =的Long.parseLong(toks [5]);
        长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]);

        回报(浮)(CPU2  -  CPU1)/((CPU2 +空闲2) - (CPU1 + IDLE1));

    }赶上(IOException异常前){
        ex.printStackTrace();
    }

    返回0;
}
 

我想这让CPU1的使用,但它不工作:

 公众持股量readUsageCPU0(){
    尝试 {

        RandomAccessFile的读者=新RandomAccessFile的(的/ proc / STAT,R);
        reader.seek(0);
        字符串负荷= reader.readLine();
        负载= reader.readLine();
        负载= reader.readLine();


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

        长IDLE1 =的Long.parseLong(toks [5]);
        长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]);

        尝试 {
            视频下载(500);
        }赶上(例外五){}

        reader.seek(0);
        负载= reader.readLine();
        负载= reader.readLine();
        负载= reader.readLine();
        reader.close();

        toks = load.split();

        长IDLE2 =的Long.parseLong(toks [5]);
        长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]);

        回报(浮)(CPU2  -  CPU1)/((CPU2 +空闲2) - (CPU1 + IDLE1));

    }赶上(IOException异常前){
        ex.printStackTrace();
    }

    返回0;
}
 

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

 字符串负荷= reader.readLine();
 

所以,我试图以获得CPU0的使用和第三个获得CPU1两次使用它。 但结果总是0或100 ......我不明白!

现在用我的正确方法? 现在用我正确的文件? 这是结果是否正常?

请帮助!

解决方案

 公共类CpuStat {
    私有静态最后字符串变量=CpuUsage;
    私人RandomAccessFile的STATFILE;
    私人cpuinfo的mCpuInfoTotal;
    私人的ArrayList< cpuinfo的> mCpuInfoList;

    公共CpuStat(){
    }

    公共无效更新(){
        尝试 {
            的CreateFile();
            parseFile();
            closeFile();
        }赶上(FileNotFoundException异常E){
            STATFILE = NULL;
            Log.e(TAG,无法打开的/ proc / STAT:+ E);
        }赶上(IOException异常E){
            Log.e(TAG,无法靠近的/ proc / STAT:+ E);
        }
    }

    私人无效的CreateFile()抛出FileNotFoundException异常{
        STATFILE =新RandomAccessFile的(的/ proc / STAT,R);
    }

    公共无效closeFile()抛出IOException异常{
        如果(STATFILE!= NULL)
            statFile.close();
    }

    私人无效parseFile(){
        如果(STATFILE!= NULL){
            尝试 {
                statFile.seek(0);
                字符串cpuLine =;
                INT CPUID = -1;
                做 {
                    cpuLine = statFile.readLine();
                    parseCpuLine(CPUID,cpuLine);
                    CPUID ++;
                }而(cpuLine!= NULL);
            }赶上(IOException异常E){
                Log.e(TAG,行动:+ E);
            }
        }
    }

    私人无效parseCpuLine(INT CPUID,串cpuLine){
        如果(cpuLine =空&安培;!&安培; cpuLine.length()大于0){
            的String []部分= cpuLine.split([] +);
            字符串cpuLabel =CPU;
            如果(件[0] .indexOf(cpuLabel)!= -1){
                createCpuInfo(CPUID,零部件);
            }
        } 其他 {
            Log.e(TAG,无法获得CPU行);
        }
    }

    私人无效createCpuInfo(INT CPUID,字符串[]部分){
        如果(CPUID == -1){
            如果(mCpuInfoTotal == NULL)
                mCpuInfoTotal =新cpuinfo的();
            mCpuInfoTotal.update(份);
        } 其他 {
            如果(mCpuInfoList == NULL)
                mCpuInfoList =新的ArrayList< cpuinfo的>();
            如果(CPUID< mCpuInfoList.size())
                mCpuInfoList.get(CPUID).update(件);
            其他 {
                cpuinfo的信息=新cpuinfo的();
                info.update(份);
                mCpuInfoList.add(信息);
            }
        }
    }

    公众诠释getCpuUsage(INT CPUID){
        更新();
        INT用法= 0;
        如果(mCpuInfoList!= NULL){
            INT cpuCount = mCpuInfoList.size();
            如果(cpuCount大于0){
                cpuCount--;
                如果(CPUID == cpuCount){// -1 CPU的总用量
                    用法= mCpuInfoList.get(0).getUsage();
                } 其他 {
                    如果(CPUID< = cpuCount)
                        用法= mCpuInfoList.get(CPUID).getUsage();
                    其他
                        用法= -1;
                }
            }
        }
        返回使用;
    }


    公众诠释getTotalCpuUsage(){
        更新();
        INT用法= 0;
        如果(mCpuInfoTotal!= NULL)
            用法= mCpuInfoTotal.getUsage();
        返回使用;
    }


    公共字符串的toString(){
        更新();
        StringBuffer的BUF =新的StringBuffer();
        如果(mCpuInfoTotal!= NULL){
            buf.append(CPU总:);
            buf.append(mCpuInfoTotal.getUsage());
            buf.append(%);
        }
        如果(mCpuInfoList!= NULL){
            的for(int i = 0; I< mCpuInfoList.size();我++){
                cpuinfo的信息= mCpuInfoList.get(我);
                buf.append(CPU核心(+ I +):);
                buf.append(info.getUsage());
                buf.append(%);
                info.getUsage();
            }
        }
        返回buf.toString();
    }

    公共类cpuinfo的{
        私人诠释mUsage;
        专用长mLastTotal;
        专用长mLastIdle;

        公共cpuinfo的(){
            mUsage = 0;
            mLastTotal = 0;
            mLastIdle = 0;
        }

        私人诠释getUsage(){
            返回mUsage;
        }

        公共无效更新(字符串[]部分){
            //列如下:
            //
            // 0CPU:字符串CPU标识线
            // 1用户:以用户方式执行正常过程
            // 2漂亮:以用户方式执行niced进程
            // 3系统:以内核方式执行过程
            // 4空闲:摆弄大拇指
            // 5 IOWAIT:等待I / O完成
            // 6 IRQ:中断服务
            // 7的softirq:服务软中断
            //
            长期闲置=的Long.parseLong(零件[4],10);
            总长= 0;
            布尔头= TRUE;
            对于(字符串部分:部分){
                如果(头){
                    头= FALSE;
                    继续;
                }
                共有+ =的Long.parseLong(部分,10);
            }
            长diffIdle =闲置 -  mLastIdle;
            长diffTotal =总 -  mLastTotal;
            mUsage =(INT)((浮动)(diffTotal  -  diffIdle)/ diffTotal * 100);
            mLastTotal =总;
            mLastIdle =闲置;
            Log.i(TAG,CPU总=+共+;闲置=+闲置+;使用=+ mUsage);
        }
    }
}
 

I develop a widget on Android which display many useful informations.

I am trying to modify this method to return the percent of use of one cpu core, in order to have the percent of use of each core !!!

On my HTC One X, i have in " /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

I use this method to return the percent of use of all cpu core.

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;
} 

I am trying this to get cpu1's use, but it's don't work:

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;
}

This allows to read one line and the cursor stay at the end of the line:

String load = reader.readLine();

So, i tried to use it twice in order to get CPU0's use and third to get CPU1. But the result is always 0 or 100 ... I don't understand !

Am i using the right way? Am i using the right file? Is this result normal?

Please HELP !!!

解决方案

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);
        }
    }
}

这篇关于如何获得在Android上的每个CPU核心的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆