Linux下,java获取CPU使用率、内存使用率

/**
 * 
 */
package com.test.cpumem;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;




/**
 * Linux下,java获取CPU使用率、内存使用率
 * @author liuhailun
 *
 */
public class CpuUsage {


private static Logger logger = Logger.getLogger(CpuUsage.class.toString().replace("class ", ""));
private static CpuUsage instance = new CpuUsage();
private CpuUsage(){

}

public static CpuUsage getCpuUsage(){
return instance;
}

private class TimeBean {
private long idleCpuTime = 0;
private long totalCpuTime = 0;

public long getTotalCpuTime() {
return totalCpuTime;
}

public void setTotalCpuTime(long totalCpuTime) {
this.totalCpuTime = totalCpuTime;
}

public long getIdleCpuTime() {
return idleCpuTime;
}

public void setIdleCpuTime(long idleCpuTime) {
this.idleCpuTime = idleCpuTime;
}
}
/**
* 采集CPU使用率 
* @return 
*/
public float get() {

//CPU利用率 = 1- (idle2-idle1)/(cpu2-cpu1)
logger.info("开始收集cpu使用率...");
float cpuUsage = 0;
Runtime runtime = Runtime.getRuntime();
try {
String command = "cat /proc/stat";
//第一次采集CPU时间
//long startTime = System.currentTimeMillis();
TimeBean timeBean1 = getCpuTimeData(runtime, command);
long idleCpuTime1 = 0,totalCpuTime1 = 0;
idleCpuTime1 = timeBean1.getIdleCpuTime();
totalCpuTime1 = timeBean1.getTotalCpuTime();
try {
Thread.sleep(100);
} catch (Exception e) {
logger.info(e.getMessage());
}
//long endTime = System.currentTimeMillis();
TimeBean timeBean2 = getCpuTimeData(runtime, command);
long idleCpuTime2 = 0,totalCpuTime2 = 0;
idleCpuTime2 = timeBean2.getIdleCpuTime();
totalCpuTime2 = timeBean2.getTotalCpuTime();
if(idleCpuTime1 != 0 && totalCpuTime1 != 0 && idleCpuTime2 != 0 && totalCpuTime2 != 0){
cpuUsage = 1 - (float)(idleCpuTime2 - idleCpuTime1) / (float)(totalCpuTime2 - totalCpuTime1);
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return cpuUsage;
}


private TimeBean getCpuTimeData(Runtime runtime, String command) throws IOException {
TimeBean timeBean = new TimeBean();
Process pro1;
// Runtime.exec 方法创建一个本机进程,并返回 Process 子类的一个实例
pro1 = runtime.exec(command);
//分别为系统启动后空闲的CPU时间和总的CPU时间
long idleCpuTime1 = 0,totalCpuTime1 = 0;
BufferedReader bR = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
String line = null;
while ((line = bR.readLine()) != null ) {
if(line.startsWith("cpu")){
line = line.trim();
logger.info(line);
String[] temp = line.split("\\s+");
idleCpuTime1 = Long.parseLong(temp[4]);
for (String s : temp) {
if(!s.startsWith("cpu")){
//CPU时间=user+system+nice+idle+iowait+irq+softirq
totalCpuTime1 += Long.parseLong(s);
}
}
logger.info("IdleCpuTime: " + idleCpuTime1 + ", " + "TotalCpuTime" + totalCpuTime1);
break;
}
}
timeBean.setIdleCpuTime(idleCpuTime1);
timeBean.setTotalCpuTime(totalCpuTime1);
bR.close();
pro1.destroy();
return timeBean;
}






/**
* @param args
*/
public static void main(String[] args) {
float cpuUse = 0;
CpuUsage cpuUsage = CpuUsage.getCpuUsage();
while (true) {
cpuUse = cpuUsage.get();
System.out.println(cpuUse);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}


}
可以使用Java的Runtime类和Process类来获取Linux服务器的CPU内存使用率。具体实现方法如下: 1. 获取CPU使用率: ```java public static double getCpuUsage() { try { Process process = Runtime.getRuntime().exec("top -b -n1"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); while (line != null) { if (line.startsWith("Cpu(s)")) { String[] cpuInfo = line.split("\\s+"); double idleCpuUsage = Double.parseDouble(cpuInfo[4]); double totalCpuUsage = 100 - idleCpuUsage; return totalCpuUsage; } line = reader.readLine(); } } catch (IOException e) { e.printStackTrace(); } return 0; } ``` 2. 获取内存使用率: ```java public static double getMemoryUsage() { try { Process process = Runtime.getRuntime().exec("free -m"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); if (line != null) { String[] memoryInfo = line.split("\\s+"); double totalMemory = Double.parseDouble(memoryInfo[1]); double usedMemory = Double.parseDouble(memoryInfo[2]); double memoryUsage = usedMemory / totalMemory * 100; return memoryUsage; } } catch (IOException e) { e.printStackTrace(); } return 0; } ``` 以上代码通过执行Linux命令获取CPU内存使用率,并返回一个double类型的数值,表示使用率的百分比。需要注意的是,这些命令的输出格式可能会因Linux版本而异,需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值