/**
* 在Linux下,计算CPU使用率
*
* @return
*/
public static double getLinuxCpu() {
Runtime runtime = Runtime.getRuntime();
try {
Process pro = runtime.exec("top -d 1 -b -n 2");//top -d 2 (null) //top -b -n 1 (no change)
LineNumberReader input = new LineNumberReader(new InputStreamReader(pro.getInputStream()));
double cpu = getContent(input);
pro.destroy();
return cpu;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 获得Linux CPU使用率.
* @return 返回cpu使用率
*/
private static double getContent(LineNumberReader input) {
double cpu = 0;
try {
String line;
while ((line = input.readLine()) != null) {
//%Cpu(s): 2.5 us, 0.5 sy, 0.0 ni, 97.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
//Cpu(s): 5.4%us, 0.7%sy, 0.0%ni, 93.8%id, 0.1%wa, 0.0%hi, 0.0%si, 0.0%st
if(line.toLowerCase().contains("cpu") && line.contains("id")){
line = line.substring(0, line.indexOf("id"));
line = line.substring(line.lastIndexOf(","));
line = line.replaceAll("(?is)[^\\d\\.]+", "");
cpu += Double.parseDouble(line);
}
}
input.close();
cpu = (100 - cpu / 2);
} catch (Exception e) {
e.printStackTrace();
}
return cpu;
}
方法二:
package com.test.cpumem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;
public class MemUsage {
private static Logger logger = Logger.getLogger(MemUsage.class.toString().replace("class ", ""));
private static MemUsage instance = new MemUsage();
private MemUsage() {
}
public static MemUsage getMemUsage() {
return instance;
}
private float get() {
logger.info("开始收集memory使用率");
float memUsage = 0.0f;
Process pro = null;
Runtime runtime = Runtime.getRuntime();
BufferedReader in = null;
try {
String command = "cat /proc/meminfo";
pro = runtime.exec(command);
in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line = null;
int count = 0;
long totalMem = 0,freeMem = 0;
while ((line = in.readLine()) != null) {
logger.info(line);
String[] memInfo = line.split("\\s+");
if(memInfo[0].startsWith("MemTotal")){
totalMem = Long.parseLong(memInfo[1]);
}
if(memInfo[0].startsWith("MemFree")){
freeMem = Long.parseLong(memInfo[1]);
}
if(totalMem != 0 && freeMem != 0){
memUsage = 1 - (float)freeMem / (float)totalMem;
logger.info("本节点内存使用率为:" + memUsage);
break;
}
}
} catch (Exception e) {
logger.info(e.getMessage());
} finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return memUsage;
}
public static void main(String[] args) {
MemUsage memUsage = MemUsage.getMemUsage();
while (true) {
System.out.println(memUsage.get());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}