-- 代码库 -->_oshi获取cp">
赞
踩
获取系统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);
}
}
}
如下是控制台打印的日志信息
2.使用sigar方法获取系统CPU、内存
使用此方法需要使用到外部组件,我这里刚好有,可以自行下载sigar百度分享地址,提取码:6ijt。
如果是Windows系统需要将sigar-amd64-winnt.dll文件放到到C:\Windows\System32
如果是Linux系统需要将libsigar-amd64-linux.so文件放到/usr/lib64
需要在maven中添加依赖:
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<repositories><!-- 代码库 -->
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public//</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
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信息
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();
}
}
}
以下是控制台打印的内存信息
3.使用oshi方法获取系统CPU、内存
需要在maven中添加依赖:
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>3.5.0</version>
</dependency>
<repositories><!-- 代码库 -->
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public//</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
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);
}
}
}
以下是打印信息
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<FORMAT){
return new DecimalFormat("#.##KB").format(kbNumber);
}
double mbNumber = kbNumber/FORMAT;
if(mbNumber<FORMAT){
return new DecimalFormat("#.##MB").format(mbNumber);
}
double gbNumber = mbNumber/FORMAT;
if(gbNumber<FORMAT){
return new DecimalFormat("#.##GB").format(gbNumber);
}
double tbNumber = gbNumber/FORMAT;
return new DecimalFormat("#.##TB").format(tbNumber);
}
}
以下是打印的信息
到此结束!
综合考虑使用oshi的方法是最好的,不用使用外部组件,准确率也是最高的。
————————————————
版权声明:本文为CSDN博主「紫伟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41866138/article/details/105386832
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。