window的cmd,该命令会实时显示 CPU 使用率
bash
typeperf "\Processor(_Total)\% Processor Time"
pom.xml依赖
xml
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.2.2</version>
</dependency>
java代码实现
java
public static void main(String[] args) {
SpringApplication.run(Iec104Application.class, args);
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardware = systemInfo.getHardware();
System.out.println(hardware.getComputerSystem());
CentralProcessor processor = hardware.getProcessor();
GlobalMemory memory = hardware.getMemory();
FileSystem fileSystem = systemInfo.getOperatingSystem().getFileSystem();
long[] prevTicks = processor.getSystemCpuLoadTicks();
// 计算CPU负载百分比
//一定要睡眠一下,不然cpu获取是平均的,不然可能是0
Util.sleep(1000);
double load = processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;
System.out.println("CPU Load: " + String.format("%.1f", load) + "%");
// 创建 DecimalFormat 对象,保留 1 位小数
DecimalFormat df = new DecimalFormat("#.0");
// 内存使用情况
long totalMemory = memory.getTotal(); // 获取总内存
double totalMemoryInGB = totalMemory / (1024.0 * 1024.0 * 1024.0); // 转换为 GB
System.out.println("system.memory.total: " + df.format(totalMemoryInGB) + " GB");
long usedMemory = totalMemory - memory.getAvailable(); // 已用内存
double usedMemoryInGB = usedMemory / (1024.0 * 1024.0 * 1024.0); // 转换为 GB
System.out.println("system.memory.used: " + df.format(usedMemoryInGB) + " GB");
// 硬盘使用情况(总空间和已用空间)
long totalDiskSpace = fileSystem.getFileStores().stream()
.mapToLong(fs -> fs.getTotalSpace())
.sum(); // 获取硬盘总空间
double totalDiskSpaceInGB = totalDiskSpace / (1024.0 * 1024.0 * 1024.0); // 转换为 GB
System.out.println("system.disk.total: " + df.format(totalDiskSpaceInGB) + " GB");
// 获取已用硬盘空间,可以读取每一个盘符
long usedDiskSpace = fileSystem.getFileStores().stream()
.mapToLong(fs -> fs.getUsableSpace())
.sum();
double usedDiskSpaceInGB = usedDiskSpace / (1024.0 * 1024.0 * 1024.0); // 转换为 GB
System.out.println("system.disk.used: " + df.format(usedDiskSpaceInGB) + " GB");
}