我想获取所有内核的总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)。