如何从java获取OS的CPU使用百分比

我想从java代码计算OS的CPU使用百分比。

  1. 有几种方法可以通过unix命令找到它[例如使用mpstat/proc/stat等…]并在Runtime.getRuntime().exec使用它Runtime.getRuntime().exec

但我不想使用系统调用。

我试过ManagementFactory.getOperatingSystemMXBean()

 OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); System.out.println(osBean.getSystemLoadAverage()); 

但它给出了cpu负载但不是cpu使用情况。 无论如何要找到使用百分比?

在Java 7中,你可以这样得到它:

 public static double getProcessCpuLoad() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem"); AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" }); if (list.isEmpty()) return Double.NaN; Attribute att = (Attribute)list.get(0); Double value = (Double)att.getValue(); // usually takes a couple of seconds before we get real values if (value == -1.0) return Double.NaN; // returns a percentage value with 1 decimal point precision return ((int)(value * 1000) / 10.0); } 

您可以使用SIGAR API 。 它是跨平台的(但我只在Windows上使用它)。

这里有Javadoc,二进制文件就在这里

它根据Apache 2.0许可证的条款获得许可。