根据之前的答案和个人经验,以下是我用来监控CPU使用情况的代码。这个类的代码是用纯Java编写的。
import java.io.IOException;
import java.io.RandomAccessFile;
public final class LinuxUtils {
private static final int FIRST_SYS_CPU_COLUMN_INDEX = 2;
private static final int IDLE_SYS_CPU_COLUMN_INDEX = 5;
public String readSystemStat() {
RandomAccessFile reader = null;
String load = null;
try {
reader = new RandomAccessFile("/proc/stat", "r");
load = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
Streams.close(reader);
}
return load;
}
public float getSystemCpuUsage(String start, String end) {
String[] stat = start.split("\\s");
long idle1 = getSystemIdleTime(stat);
long up1 = getSystemUptime(stat);
stat = end.split("\\s");
long idle2 = getSystemIdleTime(stat);
long up2 = getSystemUptime(stat);
float cpu = -1f;
if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
cpu *= 100.0f;
}
}
return cpu;
}
public long getSystemUptime(String[] stat) {
long l = 0L;
for (int i = FIRST_SYS_CPU_COLUMN_INDEX; i < stat.length; i++) {
if (i != IDLE_SYS_CPU_COLUMN_INDEX ) {
try {
l += Long.parseLong(stat[i]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
return -1L;
}
}
}
return l;
}
public long getSystemIdleTime(String[] stat) {
try {
return Long.parseLong(stat[IDLE_SYS_CPU_COLUMN_INDEX]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
return -1L;
}
public String readProcessStat(int pid) {
RandomAccessFile reader = null;
String line = null;
try {
reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
line = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
Streams.close(reader);
}
return line;
}
public float getProcessCpuUsage(String start, String end, long uptime) {
String[] stat = start.split("\\s");
long up1 = getProcessUptime(stat);
stat = end.split("\\s");
long up2 = getProcessUptime(stat);
float ret = -1f;
if (up1 >= 0 && up2 >= up1 && uptime > 0.) {
ret = 100.f * (up2 - up1) / (float) uptime;
}
return ret;
}
public long getProcessUptime(String[] stat) {
return Long.parseLong(stat[14]) + Long.parseLong(stat[15]);
}
public long getProcessIdleTime(String[] stat) {
return Long.parseLong(stat[16]) + Long.parseLong(stat[17]);
}
public float syncGetSystemCpuUsage(long elapse) {
String stat1 = readSystemStat();
if (stat1 == null) {
return -1.f;
}
try {
Thread.sleep(elapse);
} catch (Exception e) {
}
String stat2 = readSystemStat();
if (stat2 == null) {
return -1.f;
}
return getSystemCpuUsage(stat1, stat2);
}
public float syncGetProcessCpuUsage(int pid, long elapse) {
String pidStat1 = readProcessStat(pid);
String totalStat1 = readSystemStat();
if (pidStat1 == null || totalStat1 == null) {
return -1.f;
}
try {
Thread.sleep(elapse);
} catch (Exception e) {
e.printStackTrace();
return -1.f;
}
String pidStat2 = readProcessStat(pid);
String totalStat2 = readSystemStat();
if (pidStat2 == null || totalStat2 == null) {
return -1.f;
}
String[] toks = totalStat1.split("\\s");
long cpu1 = getSystemUptime(toks);
toks = totalStat2.split("\\s");
long cpu2 = getSystemUptime(toks);
return getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
}
}
有几种利用这个类的方法。您可以调用syncGetSystemCpuUsage
或syncGetProcessCpuUsage
,但每个都会阻塞调用线程。由于常见问题是同时监视总CPU使用率和当前进程的CPU使用情况,因此我设计了一个计算它们两个的类。该类包含一个专用线程。输出管理是实现特定的,您需要编写自己的代码。
该类可以通过几种方式进行自定义。常量CPU_WINDOW
定义读取深度,即读取和计算相应CPU负载之间的毫秒数。 CPU_REFRESH_RATE
是每次CPU负载测量之间的时间。不要将CPU_REFRESH_RATE
设置为0,因为它会在第一次读取后暂停线程。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import android.app.Application;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import my.app.LinuxUtils;
import my.app.Streams;
import my.app.TestReport;
import my.app.Utils;
public final class CpuUtil {
private static final int CPU_WINDOW = 1000;
private static final int CPU_REFRESH_RATE = 100;
private static HandlerThread handlerThread;
private static TestReport output;
static {
output = new TestReport();
output.setDateFormat(Utils.getDateFormat(Utils.DATE_FORMAT_ENGLISH));
}
private static boolean monitorCpu;
public static void setOutput(File dir, boolean append) {
try {
File file = new File(dir, "cpu.txt");
output.setOutputStream(new FileOutputStream(file, append));
if (!append) {
output.println(file.getAbsolutePath());
output.newLine(1);
_printLine(output, "Process", "CPU%");
output.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static boolean startCpuMonitoring() {
CpuUtil.monitorCpu = true;
handlerThread = new HandlerThread("CPU monitoring");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
while (CpuUtil.monitorCpu) {
LinuxUtils linuxUtils = new LinuxUtils();
int pid = android.os.Process.myPid();
String cpuStat1 = linuxUtils.readSystemStat();
String pidStat1 = linuxUtils.readProcessStat(pid);
try {
Thread.sleep(CPU_WINDOW);
} catch (Exception e) {
}
String cpuStat2 = linuxUtils.readSystemStat();
String pidStat2 = linuxUtils.readProcessStat(pid);
float cpu = linuxUtils
.getSystemCpuUsage(cpuStat1, cpuStat2);
if (cpu >= 0.0f) {
_printLine(output, "total", Float.toString(cpu));
}
String[] toks = cpuStat1.split(" ");
long cpu1 = linuxUtils.getSystemUptime(toks);
toks = cpuStat2.split(" ");
long cpu2 = linuxUtils.getSystemUptime(toks);
cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2,
cpu2 - cpu1);
if (cpu >= 0.0f) {
_printLine(output, "" + pid, Float.toString(cpu));
}
try {
synchronized (this) {
wait(CPU_REFRESH_RATE);
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
Log.i("THREAD CPU", "Finishing");
}
});
return CpuUtil.monitorCpu;
}
public static void stopCpuMonitoring() {
if (handlerThread != null) {
monitorCpu = false;
handlerThread.quit();
handlerThread = null;
}
}
public void dispose() {
monitorCpu = false;
if (output != null) {
OutputStream os = output.getOutputStream();
if (os != null) {
Streams.close(os);
output.setOutputStream(null);
}
output = null;
}
}
private static void _printLine(TestReport output, String process, String cpu) {
output.stampln(process + ";" + cpu);
}
}