package main;
|
|
import java.io.BufferedReader;
|
import java.io.FileInputStream;
|
import java.io.InputStreamReader;
|
import java.io.LineNumberReader;
|
import java.math.BigDecimal;
|
import java.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.StringTokenizer;
|
|
public class ComputerMonitorUtil {
|
private static String osName = System.getProperty("os.name");
|
private static final int CPUTIME = 500;
|
private static final int PERCENT = 100;
|
private static final int FAULTLENGTH = 10;
|
|
/**
|
* ¹¦ÄÜ£º»ñÈ¡LinuxºÍWindowϵͳcpuʹÓÃÂÊ
|
* */
|
public static double getCpuUsage() {
|
// Èç¹ûÊÇwindowϵͳ
|
if (osName.toLowerCase().contains("windows")
|
|| osName.toLowerCase().contains("win")) {
|
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));//µÚÒ»´Î¶ÁÈ¡CPUÐÅÏ¢
|
Thread.sleep(CPUTIME);//˯500ms
|
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));//µÚ¶þ´Î¶ÁÈ¡CPUÐÅÏ¢
|
if (c0 != null && c1 != null) {
|
long idletime = c1[0] - c0[0];//¿ÕÏÐʱ¼ä
|
long busytime = c1[1] - c0[1];//ʹÓÃʱ¼ä
|
Double cpusage = Double.valueOf(PERCENT * (busytime) * 1.0 / (busytime + idletime));
|
BigDecimal b1 = new BigDecimal(cpusage);
|
double cpuUsage = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
|
return cpuUsage;
|
} else {
|
return 0.0;
|
}
|
} catch (Exception ex) {
|
ex.printStackTrace();
|
return 0.0;
|
}
|
} else {
|
try {
|
Map<?, ?> map1 = ComputerMonitorUtil.cpuinfo();
|
Thread.sleep(CPUTIME);
|
Map<?, ?> map2 = ComputerMonitorUtil.cpuinfo();
|
|
long user1 = Long.parseLong(map1.get("user").toString());
|
long nice1 = Long.parseLong(map1.get("nice").toString());
|
long system1 = Long.parseLong(map1.get("system").toString());
|
long idle1 = Long.parseLong(map1.get("idle").toString());
|
|
long user2 = Long.parseLong(map2.get("user").toString());
|
long nice2 = Long.parseLong(map2.get("nice").toString());
|
long system2 = Long.parseLong(map2.get("system").toString());
|
long idle2 = Long.parseLong(map2.get("idle").toString());
|
|
long total1 = user1 + system1 + nice1;
|
long total2 = user2 + system2 + nice2;
|
float total = total2 - total1;
|
|
long totalIdle1 = user1 + nice1 + system1 + idle1;
|
long totalIdle2 = user2 + nice2 + system2 + idle2;
|
float totalidle = totalIdle2 - totalIdle1;
|
|
float cpusage = (total / totalidle) * 100;
|
|
BigDecimal b1 = new BigDecimal(cpusage);
|
double cpuUsage = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
|
return cpuUsage;
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
}
|
}
|
return 0;
|
}
|
|
/**
|
* ¹¦ÄÜ£ºLinux CPUʹÓÃÐÅÏ¢
|
* */
|
public static Map<?, ?> cpuinfo() {
|
InputStreamReader inputs = null;
|
BufferedReader buffer = null;
|
Map<String, Object> map = new HashMap<String, Object>();
|
try {
|
inputs = new InputStreamReader(new FileInputStream("/proc/stat"));
|
buffer = new BufferedReader(inputs);
|
String line = "";
|
while (true) {
|
line = buffer.readLine();
|
if (line == null) {
|
break;
|
}
|
if (line.startsWith("cpu")) {
|
StringTokenizer tokenizer = new StringTokenizer(line);
|
List<String> temp = new ArrayList<String>();
|
while (tokenizer.hasMoreElements()) {
|
String value = tokenizer.nextToken();
|
temp.add(value);
|
}
|
map.put("user", temp.get(1));
|
map.put("nice", temp.get(2));
|
map.put("system", temp.get(3));
|
map.put("idle", temp.get(4));
|
map.put("iowait", temp.get(5));
|
map.put("irq", temp.get(6));
|
map.put("softirq", temp.get(7));
|
map.put("stealstolen", temp.get(8));
|
break;
|
}
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
buffer.close();
|
inputs.close();
|
} catch (Exception e2) {
|
e2.printStackTrace();
|
}
|
}
|
return map;
|
}
|
|
// window¶ÁÈ¡cpuÏà¹ØÐÅÏ¢
|
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
|
String caption = substring(line, capidx, cmdidx - 1).trim();
|
// System.out.println("caption:"+caption);
|
String cmd = substring(line, cmdidx, kmtidx - 1).trim();
|
// System.out.println("cmd:"+cmd);
|
if (cmd.indexOf("wmic.exe") >= 0) {
|
continue;
|
}
|
String s1 = substring(line, kmtidx, rocidx - 1).trim();
|
String s2 = substring(line, umtidx, wocidx - 1).trim();
|
List<String> digitS1 = getDigit(s1);
|
List<String> digitS2 = getDigit(s2);
|
|
// System.out.println("s1:"+digitS1.get(0));
|
// System.out.println("s2:"+digitS2.get(0));
|
|
if (caption.equals("System Idle Process") || caption.equals("System")) {
|
if (s1.length() > 0) {
|
if (!digitS1.get(0).equals("") && digitS1.get(0) != null) {
|
idletime += Long.valueOf(digitS1.get(0)).longValue();
|
}
|
}
|
if (s2.length() > 0) {
|
if (!digitS2.get(0).equals("") && digitS2.get(0) != null) {
|
idletime += Long.valueOf(digitS2.get(0)).longValue();
|
}
|
}
|
continue;
|
}
|
if (s1.length() > 0) {
|
if (!digitS1.get(0).equals("") && digitS1.get(0) != null) {
|
kneltime += Long.valueOf(digitS1.get(0)).longValue();
|
}
|
}
|
|
if (s2.length() > 0) {
|
if (!digitS2.get(0).equals("") && digitS2.get(0) != null) {
|
kneltime += Long.valueOf(digitS2.get(0)).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;
|
}
|
|
/**
|
* ´Ó×Ö·û´®Îı¾ÖлñµÃÊý×Ö
|
*
|
* @param text
|
* @return
|
*/
|
private static List<String> getDigit(String text) {
|
List<String> digitList = new ArrayList<String>();
|
digitList.add(text.replaceAll("\\D", ""));
|
return digitList;
|
}
|
|
/**
|
* ÓÉÓÚString.subString¶Ôºº×Ö´¦Àí´æÔÚÎÊÌ⣨°ÑÒ»¸öºº×ÖÊÓΪһ¸ö×Ö½Ú)£¬Òò´ËÔÚ °üº¬ºº×ÖµÄ×Ö·û´®Ê±´æÔÚÒþ»¼£¬ÏÖµ÷ÕûÈçÏ£º
|
*
|
* @param src
|
* Òª½ØÈ¡µÄ×Ö·û´®
|
* @param start_idx
|
* ¿ªÊ¼×ø±ê£¨°üÀ¨¸Ã×ø±ê)
|
* @param end_idx
|
* ½ØÖ¹×ø±ê£¨°üÀ¨¸Ã×ø±ê£©
|
* @return
|
*/
|
private static String substring(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;
|
}
|
/*
|
public static void main(String[] args) throws Exception {
|
|
double cpuUsage = ComputerMonitorUtil.getCpuUsage();
|
|
System.out.println("cpuUsage:"+cpuUsage);
|
}
|
*/
|
}
|