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

时间:2018-06-05 09:41:31

标签: java performance cpu monitoring cpu-usage

我想获得所有核心的总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。 有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

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