/**
*
* @Title: 获取cpu使用率
* @Description: TODO
* @return
*/
public static String getCpuRatio() {
String cpuRatio;//cpu使用率
String isWindowsOrLinux = isWindowsOrLinux();
try {
if (isWindowsOrLinux.equals(WINDOWS)) { // 判断操作系统类型
cpuRatio = getCpuRatioForWindows() + "";
} else {
cpuRatio = getCpuInfo();
}
} catch (Exception e) {
cpuRatio = "0";
}
return cpuRatio;
}
/**
* 判断是服务器的系统类型是Windows 还是 Linux
*
* @return
*/
public static String isWindowsOrLinux() {
String osName = System.getProperty("os.name");
String sysName = "";
if (osName.toLowerCase().startsWith("windows")) {
sysName = "windows";
} else if (osName.toLowerCase().startsWith("linux")) {
sysName = "linux";
}
return sysName;
}
/**
* 获得CPU使用率. windows
*
* @return 返回cpu使用率
*/
private static double 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(1000);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return Double.valueOf(
PERCENT * (busytime) / (busytime + idletime))
.doubleValue();
} else {
return 0.0;
}
} catch (Exception ex) {
// ex.printStackTrace();
return 0.0;
}
}
/** */
/**
* 读取CPU信息.
*
* @param proc
* @return
* @author amg * Creation date: 2008-4-25 - 下午06:10:14
*/
private static 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() < FAULTLENGTH) {
return null;
}
int capidx = line.indexOf("Caption");
int cmdidx = line.indexOf("CommandLine");
int rocidx = line.indexOf("ReadOperationCount");
int umtidx = line.indexOf("UserModeTime");
int kmtidx = line.indexOf("KernelModeTime");
int wocidx = line.indexOf("WriteOperationCount");
long idletime = 0;
long kneltime = 0;
long usertime = 0;
while ((line = input.readLine()) != null) {
if (line.length() < wocidx) {
continue;
}
// 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
// ThreadCount,UserModeTime,WriteOperation
String caption = Bytes.substring(line, capidx, cmdidx - 1)
.trim();
String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
if (caption.equals("System Idle Process")
|| caption.equals("System")) {
idletime += Long.valueOf(
Bytes.substring(line, kmtidx, rocidx - 1).trim())
.longValue();
idletime += Long.valueOf(
Bytes.substring(line, umtidx, wocidx - 1).trim())
.longValue();
continue;
}
String kneltimeTmp = Bytes.substring(line, kmtidx, rocidx - 1)
.trim();
String usertimeTmp = Bytes.substring(line, umtidx, wocidx - 1)
.trim();
if (kneltimeTmp != null && !"".equals(kneltimeTmp)) {
kneltime += Long.valueOf(kneltimeTmp).longValue();
}
if (usertimeTmp != null && !"".equals(usertimeTmp)) {
usertime += Long.valueOf(usertimeTmp).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;
}
/**
* 获得Linux cpu使用率
*
* @return float efficiency
* @throws IOException
* @throws InterruptedException
*/
public static String getCpuInfo() throws IOException, InterruptedException {
File file = new File("/proc/stat");
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
StringTokenizer token = new StringTokenizer(br.readLine());
token.nextToken();
long user1 = Long.parseLong(token.nextToken() + "");
long nice1 = Long.parseLong(token.nextToken() + "");
long sys1 = Long.parseLong(token.nextToken() + "");
long idle1 = Long.parseLong(token.nextToken() + "");
Thread.sleep(1000);
br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
token = new StringTokenizer(br.readLine());
token.nextToken();
long user2 = Long.parseLong(token.nextToken());
long nice2 = Long.parseLong(token.nextToken());
long sys2 = Long.parseLong(token.nextToken());
long idle2 = Long.parseLong(token.nextToken());
String cpuPercent = String
.valueOf((float) ((user2 + sys2 + nice2) - (user1 + sys1 + nice1))
* 100
/ (float) ((user2 + nice2 + sys2 + idle2) - (user1
+ nice1 + sys1 + idle1)));
return cpuPercent;
}