/**
* 获取cpu使用率
* @return
*/
public static float getCpuUsed() {
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[5])+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
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[5])+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
Log.d(TAG, "idle1:"+idle1+",cpu1:"+cpu1+",idle2:"+idle2+",cpu1:"+cpu2);
return (float) ((cpu2 - idle2) - (cpu1 - idle1))/ (cpu2 -cpu1);
//return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
获取cpu使用率
最新推荐文章于 2024-05-29 20:25:17 发布