Skip to content Skip to sidebar Skip to footer

How To Get Usage Of Each Cpu Core On Android

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 o

Solution 1:

publicclassCpuStat {
    privatestatic final String TAG = "CpuUsage";
    private RandomAccessFile statFile;
    private CpuInfo mCpuInfoTotal;
    private ArrayList<CpuInfo> mCpuInfoList;

    publicCpuStat() {
    }

    publicvoidupdate() {
        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);
        }
    }

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

    publicvoidcloseFile() throws IOException {
        if (statFile != null)
            statFile.close();
    }

    privatevoidparseFile() {
        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);
            }
        }
    }

    privatevoidparseCpuLine(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");
        }
    }

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

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


    publicintgetTotalCpuUsage() {
        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();
    }

    publicclassCpuInfo {
        privateint  mUsage;            
        privatelong mLastTotal;
        privatelong mLastIdle;

        publicCpuInfo() {
            mUsage = 0;
            mLastTotal = 0;
            mLastIdle = 0;  
        }

        privateintgetUsage() {
            return mUsage;
        }

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

Solution 2:

You can get the frequency of each core with this...

try {
     double currentFreq;
     RandomAccessFile readerCurFreq;
     readerCurFreq = new RandomAccessFile("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", "r");
     String curfreg = readerCurFreq.readLine();
     currentFreq = Double.parseDouble(curfreg) / 1000;
     readerCurFreq.close();
     String finalfre = "Curent Frequency of Core 0 is" + currentFreq;
 } catch (IOException ex) {
     String finalfre = "Core is Idle";
    ex.printStackTrace();
 }

loop this through the number of cores. So that you can get the frequency for all the cores. Some times if the core is idle or stopped, this code may produce a exception. handle it and you're good to go

Solution 3:

thanks for nice answer of user1549150. but not works in my case. i was porting your java code into native, but it gives wrong difTotal and difIdle when java.

for me, /proc/stat as shown here,

1st

*cpu26263876180 85223679115402469 1213138 000cpu04991892940 3894231952572589842863 000cpu17115241036 147360199074367011132000cpu27033551085 15657719898135911465000cpu37123181118 15887519784126181178000intr58674412000000000000000000200..

2nd

*cpu26266226180 85229679116552469 1213138 000cpu04992352940 3894481952603589842863 000cpu17115801036 147372199077767011132000cpu27034161085 15658919898425911465000cpu37123891118 15888519784326181178000intr58679023000000000000000000200...

and parsed diftime is

  CPU difTot[410] difIdle[115]
  CPU difTot[102] difIdle[31]
  CPU difTot[102] difIdle[34]
  CPU difTot[102] difIdle[29]
  CPU difTot[101] difIdle[20]

which gives proper core usage time below.

  CORE[0] tot[11402481] idl[7911655] use[71]
  CORE[1] tot[2847762] idl[1952603] use[69]
  CORE[2] tot[2851578] idl[1990777] use[66]
  CORE[3] tot[2851602] idl[1989842] use[71]
  CORE[4] tot[2851531] idl[1978432] use[80]

final toString gives

CPUUsage :Tot[71]Core0[69]Core1[66]Core2[71]Core3[80]

my devies is galaxy note2(rooted)

here is source code. hope may someone will given salvation.

//GQPHD(bispro89@gmail.com)voidprintCpuState(){
std::ifstream is("/proc/stat");
std::stringstream buffer;
buffer << is.rdbuf();
std::string strbuff(buffer.str());

LOGV("********** start /proc/stat log\n* %s\n********** end /proc/stat log",strbuff.c_str());
std::vector<std::string> vec;
vec = Tokenize(strbuff);

//@ref http://stackoverflow.com/questions/11739444/how-to-get-usage-of-each-cpu-core-on-androidint cntcpu = 0;
for(int i = 0 ; i < vec.capacity(); i++){
    std::string str = vec[i];
    if( (str.find("cpu") != string::npos ) )  {//if contains str// 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 = atol(vec[i+4].c_str());//Long.parseLong(parts[4], 10);long total = 0;
        bool head = true;
        for(int j = 0 ; j < 7; j++){
            total += atol(vec[i+j+1].c_str());
        }
        long diffIdle   =   idle - mLastIdle[cntcpu];
        long diffTotal  =   total - mLastTotal[cntcpu];
        int usage = (int)((float)(diffTotal - diffIdle) / diffTotal * 100);
        mUsage[cntcpu] = usage;
        mLastTotal[cntcpu] = total;
        mLastIdle[cntcpu] = idle;

        LOGV("CPU difTot[%d] difIdle[%d]",diffTotal,diffIdle);

        cntcpu++;
    }

}
for(int i = 0 ; i < 5 ; i++){
    LOGV("CORE[%d] tot[%d] idl[%d] use[%d]",i,mLastTotal[i],mLastIdle[i],mUsage[i]);
}

LOGV("CPU Usage :Tot[%d\%] Core0[%d\%] Core1[%d\%] Core2[%d\%] Core3[%d\%]",
        mUsage[0],
        mUsage[1],
        mUsage[2],
        mUsage[3],
        mUsage[4]
);
is.close();
}

thnx user1549150

Post a Comment for "How To Get Usage Of Each Cpu Core On Android"