重點就是那個wmic(Windows Management Instrumentation Command-line),
有點像是在查資料庫的感覺.
從哪裡抄來的呢? 忘記了
查到之後, 發現不用動用到JNI感覺真愉快...
如果是linux, 有以下的寫法
Process proc = Runtime.getRuntime().exec(command);
InputStream is = new BufferedInputStream(proc.getInputStream());
private String getCpuRatioForWindows(){
try {
String procCmd = System.getenv("windir")
+ "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
+ "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
Thread.sleep(5000);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
double result = Double.valueOf(100 * (busytime) / (busytime + idletime)).doubleValue();
return result + "%";
} else {
return "Can't get CPU usage";
}
} catch (Exception ex) {
ex.printStackTrace();
return "Can't get CPU usage";
}
}
private long[] readCpu(final Process proc){
long[] retn = new long[2];
try {
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line = input.readLine();
if (line == null || line.length() < capidx =" line.indexOf(" cmdidx =" line.indexOf(" rocidx =" line.indexOf(" umtidx =" line.indexOf(" kmtidx =" line.indexOf(" wocidx =" line.indexOf(" idletime =" 0;" kneltime =" 0;" usertime =" 0;" line =" input.readLine())" caption =" cpusubstring(line," cmd =" cpusubstring(line,">= 0) {
continue;
}
// log.info("line="+line);
if (caption.equals("System Idle Process")
|| caption.equals("System")) {
idletime += Long.valueOf(
cpusubstring(line, kmtidx, rocidx - 1).trim())
.longValue();
idletime += Long.valueOf(
cpusubstring(line, umtidx, wocidx - 1).trim())
.longValue();
continue;
}
kneltime += Long.valueOf(
cpusubstring(line, kmtidx, rocidx - 1).trim())
.longValue();
usertime += Long.valueOf(
cpusubstring(line, umtidx, wocidx - 1).trim())
.longValue();
}
retn[0] = idletime;
retn[1] = kneltime + usertime;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public String cpusubstring(String src, int start_idx, int end_idx){
byte[] b = src.getBytes();
String tgt = "";
for(int i=start_idx; i<=end_idx; i++){ tgt +=(char)b[i]; } return tgt; }
No comments:
Post a Comment