我想获得所有核心的总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
。
有人可以帮我这个吗?
答案 0 :(得分:1)
JavaSysMon使用特定于操作系统的方法,例如在Linux上它解析/proc/cpuinfo
来枚举核心。对于实际的CPU核心利用率,它会解析/proc/stat
文件(请参阅LinuxMonitor)。