java获取系统CPU和内存使用率的三种方法

获取系统CPU和内存的三种方法:

1、使用OperatingSystemMXBean获取

2、使用sigar方法获取

3、使用oshi方法获取

以下是我在我的机子上对三种方法测试的比较

方法 准确率
OperatingSystemMXBean 获取的内存数据准确,CPU差距有点大
sigar 获取的内存数据稍微有点差距,CPU相对OSMXB好一点
oshi 获取的内存数据准确,CPU相对于其他两种方法差距最小

第二种和第三种方法还适用于Linux系统

1、使用OperatingSystemMXBean获取系统CPU、内存

import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;

import lombok.extern.slf4j.Slf4j;

@SuppressWarnings("restriction")
@Slf4j
public class test {
	
	private static OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
	
	public static void main(String[] args) throws InterruptedException {
		
		while(true) {
			
			//获取CPU
			double cpuLoad = osmxb.getSystemCpuLoad();
			int percentCpuLoad = (int) (cpuLoad * 100);
			//获取内存
			double totalvirtualMemory = osmxb.getTotalPhysicalMemorySize();
			double freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
			double value = freePhysicalMemorySize/totalvirtualMemory;
			int percentMemoryLoad = (int) ((1-value)*100);
			
			log.info("CPU = {},Mem = {}", percentCpuLoad,percentMemoryLoad);
			Thread.sleep(1000);
			
		}
		
	}

}

如下是控制台打印的日志信息
java获取系统CPU和内存使用率的三种方法_第1张图片

2.使用sigar方法获取系统CPU、内存

使用此方法需要使用到外部组件,我这里刚好有,可以自行下载sigar百度分享地址,提取码:6ijt。
如果是Windows系统需要将sigar-amd64-winnt.dll文件放到到C:\Windows\System32
如果是Linux系统需要将libsigar-amd64-linux.so文件放到/usr/lib64
需要在maven中添加依赖:

	
        org.fusesource
        sigar
        1.6.4
    

	
        
            maven-ali
            http://maven.aliyun.com/nexus/content/groups/public//
            
                true
            
            
                true
                always
                fail
            
        
    

sigar获取CPU信息代码

import java.util.Properties;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class test {
	
	public static void main(String[] args) throws InterruptedException, SigarException {
		
		while(true) {
			
	    	Properties props = System.getProperties();
	        String systemName = props.getProperty("os.name");
	        
	        Sigar sigar = new Sigar();
	        CpuInfo[] infos = sigar.getCpuInfoList();
	        CpuInfo infoss = infos[0];
	        CpuPerc cpu = sigar.getCpuPerc();
	        Integer totalCPUs = infoss.getTotalCores();
	        String CPUinfo = infoss.getVendor() + "  " + infoss.getModel();
	        double referenceSpeed = infoss.getMhz();
	        String CPUSpeed = String.format("%.2f", referenceSpeed / 1000) + " GHz";
	        double cpuUsedPerc = cpu.getCombined();
	        
	        String CPUPers = "";
	        if(systemName.startsWith("win") || systemName.startsWith("Win")) {
	        	CPUPers = String.format("%.1f", cpuUsedPerc * 100) + "%";
	        }else {
	        	CPUPers = String.format("%.1f", cpuUsedPerc * 1000) + "%";
	        }
	        
	        log.info("CPU信息 = {},CPU总数 = {},CPU基准速度 ={},CPU利用率 ={}",CPUinfo,totalCPUs,CPUSpeed,CPUPers);
	        Thread.sleep(1000);
	        sigar.close();
		}
		
	}

}

以下是控制台打印的CPU信息
shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxODY2MTM4,size_16,color_FFFFFF,t_70)
sigar获取内存信息代码

import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class test {
	
	public static void main(String[] args) throws InterruptedException, SigarException {
		
		while(true) {
			
	        Sigar sigar = new Sigar();
	        double memTotal = sigar.getMem().getTotal();
	        double memUsedPerc = sigar.getMem().getUsedPercent();
	
	        String memory = String.format("%.0f", memTotal / 1024 / 1024 / 1024) + " GB";
	        String memoryUsage = String.format("%.2f", memUsedPerc) + " %";
	
	        log.info("内存 = {},内存使用率 = {}",memory,memoryUsage);
	        Thread.sleep(1000);
	        sigar.close();
		}
		
	}

}

以下是控制台打印的内存信息
java获取系统CPU和内存使用率的三种方法_第2张图片

3.使用oshi方法获取系统CPU、内存

需要在maven中添加依赖:

		
            com.github.oshi
            oshi-core
            3.5.0
        

		
	        
	            maven-ali
	            http://maven.aliyun.com/nexus/content/groups/public//
	            
	                true
	            
	            
	                true
	                always
	                fail
	            
	        
	    

oshi获取CPU代码

import java.text.DecimalFormat;
import org.hyperic.sigar.SigarException;
import lombok.extern.slf4j.Slf4j;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;

@Slf4j
public class test {
	
	public static void main(String[] args) throws InterruptedException, SigarException {
		
		while(true) {
	        SystemInfo systemInfo = new SystemInfo();
	        CentralProcessor processor = systemInfo.getHardware().getProcessor();
	        long[] prevTicks = processor.getSystemCpuLoadTicks();
	        long[] ticks = processor.getSystemCpuLoadTicks();
	        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
	        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
	        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
	        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
	        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
	        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
	        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
	        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
	        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
	        
	        log.info("CPU总数 = {},CPU利用率 ={}",processor.getLogicalProcessorCount(),new DecimalFormat("#.##%").format(1.0-(idle * 1.0 / totalCpu)));
	        Thread.sleep(1000);
		}
		
	}

}

以下是打印信息
java获取系统CPU和内存使用率的三种方法_第3张图片
oshi获取内存信息代码

import java.text.DecimalFormat;
import org.hyperic.sigar.SigarException;
import lombok.extern.slf4j.Slf4j;
import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;

@Slf4j
public class test {
	
	public static void main(String[] args) throws InterruptedException, SigarException {
		
		while(true) {
	        SystemInfo systemInfo = new SystemInfo();
	        GlobalMemory memory = systemInfo.getHardware().getMemory();
	        long totalByte = memory.getTotal();
	        long acaliableByte = memory.getAvailable();
			
	        log.info("内存大小 = {},内存使用率 ={}",formatByte(totalByte),new DecimalFormat("#.##%").format((totalByte-acaliableByte)*1.0/totalByte));
	        Thread.sleep(1000);
		}
		
	}
	
	public static String formatByte(long byteNumber){
        double FORMAT = 1024.0;
        double kbNumber = byteNumber/FORMAT;
        if(kbNumber

以下是打印的信息
java获取系统CPU和内存使用率的三种方法_第4张图片
到此结束!
综合考虑使用oshi的方法是最好的,不用使用外部组件,准确率也是最高的。

你可能感兴趣的:(java获取系统CPU和内存使用率的三种方法)