Linux下使用java获取cpu、内存使用率

思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类的exec()方法执行命令"top”,获取"top"的输出,从而得到CPU和内存的使用情况。

使用top命令获取系统信息: 

top -b -n -1 | sed -n '3p'(使用sed命令将top输出内容中的第三行打印出来)

%Cpu(s):  6.5 us,  2.2 sy,  0.7 ni, 87.0 id,  3.5 wa,  0.0 hi,  0.1 si,  0.0 st

top -b -n 1 | sed -n '3p' | awk '{print $8}'(将第三行第八列打印出来)

87.0

获取单个进程CPU,内存的占用率 

cmd脚本命令:top -b -n 1 -p $pid |  sed -n '$p' 
上面的$pid,就是进程的PID 

Java Runtime类

每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。 

应用程序不能创建自己的 Runtime 类实例。


示例程序(针对suse平台,如果是其他Linux,可能需要稍微修改程序)

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MySystem {

	public static float getCpuUsage() {
		float cpuUsage = 0;
		float idleUsage = 0;
		Runtime rt = Runtime.getRuntime();
		String[] cmd = { "/bin/sh", "-c",
				"top -b -n 1 | sed -n '3p' | awk '{print $5}'" };<span style="color:#ff0000;"><strong>//如果使用的命令带有空格、重定向等,必须使用命令串(字符串数组)</strong></span>
		BufferedReader in = null;
		String str = "";
		try{
		Process p = rt.exec(cmd);
		in = new BufferedReader(new InputStreamReader(p.getInputStream()));
		str = in.readLine();
		}catch(Exception e){
			
		}
		str = str.substring(0,3);
		idleUsage = Float.parseFloat(str);
		cpuUsage = 100 - idleUsage;
		cpuUsage = FormatFloat.formatFloat(cpuUsage);
		System.out.println("CpuUsage:");
		System.out.println("	"+cpuUsage);
		return cpuUsage;
	}
	
	public static void getCPUMEMByPID(){
		Runtime rt = Runtime.getRuntime();
		String[] cmd = { "/bin/sh", "-c",
				"top -b -n 1 | sed -n '3p' | awk '{print $5}'" };
		BufferedReader in = null;
		String str = "";
		try{
		Process p = rt.exec(cmd);
		in = new BufferedReader(new InputStreamReader(p.getInputStream()));
		str = in.readLine();
		}catch(Exception e){
			
		}
	}
	
	public static float getMemUsage() {
		long memUsed = 0;
		long memTotal = 0;
		float memUsage = 0;
		Runtime rt = Runtime.getRuntime();
		String[] cmd = { "/bin/sh", "-c",
				"top -b -n 1 | sed -n '4p' | awk '{print $2 \"\t\" $4}'" };
		BufferedReader in = null;
		String str = "";
		try{
			Process p = rt.exec(cmd);
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			str = in.readLine();
		}catch(Exception e){
			
		}
		
		String[] mems = str.split("\t");
		mems[0] = mems[0].substring(0,mems[0].length()-2);
		memTotal = Long.parseLong(mems[0]);
		mems[1] = mems[1].substring(0,mems[1].length()-2);
		memUsed = Long.parseLong(mems[1]);
		memUsage = (float) memUsed / memTotal * 100;
		memUsage = FormatFloat.formatFloat(memUsage);
		System.out.println("MemUsage:");
		System.out.println("	"+memUsage);
		return memUsage;
	}

}

获取cpu、内存的使用率还有其他方法

proc文件系统(http://www.cnblogs.com/yoleung/articles/1638922.html,http://blog.csdn.net/blue_jjw/article/details/8741000)

参考文章:http://zengjz88.iteye.com/blog/1595535 http://cumtyjp.blog.163.com/blog/static/7611480820093157512732/ http://blog.csdn.net/hemingwang0902/article/details/4054709

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java代码调用Linux命令获取CPU内存使用率获取CPU使用率: ```java public static double getCpuUsage() throws IOException { double cpuUsage = 0.0; Process process = Runtime.getRuntime().exec("top -b -n1"); try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while((line = reader.readLine()) != null) { if(line.startsWith("Cpu(s)")) { String[] cpuInfo = line.split("\\s+"); double user = Double.parseDouble(cpuInfo[1].replace("%","")); double sys = Double.parseDouble(cpuInfo[3].replace("%","")); double idle = Double.parseDouble(cpuInfo[7].replace("%","")); cpuUsage = (user + sys) / (user + sys + idle) * 100.0; } } } return cpuUsage; } ``` 获取内存使用率: ```java public static double getMemoryUsage() throws IOException { double memoryUsage = 0.0; Process process = Runtime.getRuntime().exec("free -m"); try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while((line = reader.readLine()) != null) { if(line.startsWith("Mem:")) { String[] memoryInfo = line.split("\\s+"); double used = Double.parseDouble(memoryInfo[2]); double total = Double.parseDouble(memoryInfo[1]); memoryUsage = used / total * 100.0; } } } return memoryUsage; } ``` 这里使用Linux命令`top -b -n1`和`free -m`来获取CPU内存使用率。`-b`表示以批处理模式运行,不需要交互式输入。`-n1`表示只执行一次。获取到命令输出后,使用Java代码解析命令输出并计算出使用率
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值