如何从java获取操作系统的CPU使用率百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18489273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:06:35  来源:igfitidea点击:

How to get percentage of CPU usage of OS from java

javajmx

提问by G.S

I want to calculate percentage of CPU usage of OS from java code.

我想从 java 代码计算操作系统的 CPU 使用率的百分比。

  1. There are several ways to find it by unixcommand [e.g. using mpstat, /proc/statetc...] and use it from Runtime.getRuntime().exec
  1. 有几种方法被找到它unix的命令[例如,使用mpstat/proc/stat等...],并用它从Runtime.getRuntime().exec

But I don't want to use the system calls.

但我不想使用系统调用。

I tried ManagementFactory.getOperatingSystemMXBean()

我试过 ManagementFactory.getOperatingSystemMXBean()

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

But it gives the cpu load but not the cpu usage. Is there anyway to find the usage percentage?

但它提供了 cpu 负载而不是 cpu 使用率。反正有没有找到使用百分比?

回答by Julien

You can use the SIGAR API. It is cross platform ( but I've only use it on Windows).

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

The Javadoc is available hereand the binaries are here

Javadoc在此处可用,二进制文件在此处

It is licensed under the terms of the Apache 2.0 license.

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

回答by isapir

In Java 7 you can get it like so:

在 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);
}