本文总共6673个字,阅读需23分钟,全文加载时间:2.540s,本站综合其他专栏收录该内容! 字体大小:

文章导读:原文来自:https://blog.csdn.net/qq_41866138/article/details/105386832 获取系统CPU和内存的三种方法: 1、使用OperatingSystemMXBean获取 2、使用sigar方法获取 3、使用oshi方法获取 以下是我在我的机子上对三……各位看官请向下阅读:

原文来自:https://blog.csdn.net/qq_41866138/article/details/105386832

获取系统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);

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

如下是控制台打印的日志信息

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>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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();

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

以下是控制台打印的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();

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

以下是控制台打印的内存信息

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

需要在maven中添加依赖:

<dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>5.7.1</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;@Slf4jpublic 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;@Slf4jpublic 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的方法是最好的,不用使用外部组件,准确率也是最高的。

以上内容由优质教程资源合作伙伴 “鲸鱼办公” 整理编辑,如果对您有帮助欢迎转发分享!

你可能对这些文章感兴趣:

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注