[Android] How to calculate CPU usage
這邊已經快變工作筆記用的了... :S
Reference: /proc/stat explained
// Informations about kernel are available in the stat file
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" ");
// Get the jitters of the IDLE time
long oldIdle = Long.parseLong(toks[5]);
// Get the jitters of the other cpu time
long OldCpu = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
// To measure every 500 ms
Thread.sleep(500);
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" ");
// Get the CPU time again
long newIdle = Long.parseLong(toks[5]);
long newCpu = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
// Calculate the average value
float avgUsage = (float)(newCpu - oldCpu) / ((newCpu + newIdle) - (oldCpu + oldIdle));
Reference: /proc/stat explained
留言