gpt4 book ai didi

Java获取CPU核心使用率百分比

转载 作者:行者123 更新时间:2023-12-02 02:06:32 26 4
gpt4 key购买 nike

我想获得所有核心的 CPU 总使用率。我需要打印这样的内容:

Cpu 1: 33%
Cpu 2: 12%
Cpu 3: 66%
Cpu 4: 100%

我尝试使用此代码:

OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
long prevUpTime = runtimeMXBean.getUptime();
long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
double cpuUsage;
try
{
Thread.sleep(500);
}
catch (Exception ignored) { }

operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long upTime = runtimeMXBean.getUptime();
long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
long elapsedCpu = processCpuTime - prevProcessCpuTime;
long elapsedTime = upTime - prevUpTime;

cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
System.out.println("Java CPU: " + cpuUsage);

但是这段代码给了我这样的输出:Java CPU: 27.504911422729492。有人可以帮我解决这个问题吗?

最佳答案

JavaSysMon使用特定于操作系统的方法,例如在 Linux 上,它解析/proc/cpuinfo 来枚举内核。对于实际的 CPU 核心利用率,它会解析 /proc/stat 文件(请参阅 LinuxMonitor )。

关于Java获取CPU核心使用率百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com