如何从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
How to get percentage of CPU usage of OS from java
提问by G.S
I want to calculate percentage of CPU usage of OS from java code.
我想从 java 代码计算操作系统的 CPU 使用率的百分比。
- There are several ways to find it by
unix
command [e.g. usingmpstat
,/proc/stat
etc...] and use it fromRuntime.getRuntime().exec
- 有几种方法被找到它
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
回答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);
}