如何从java获取OS的CPU使用百分比 [英] How to get percentage of CPU usage of OS from java

查看:747
本文介绍了如何从java获取OS的CPU使用百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


  1. 有几种方法可以通过<$ c找到它$ c> unix 命令[例如使用 mpstat / proc / stat etc ...]并从运行时使用它。 getRuntime()。exec

  1. There are several ways to find it by unix command [e.g. using mpstat, /proc/stat etc...] and use it from Runtime.getRuntime().exec

但我不想使用系统调用。

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

我试过 ManagementFactory.getOperatingSystemMXBean()

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

但是它给出了cpu加载而不是cpu使用。有没有找到使用百分比?

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

推荐答案

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

In Java 7 you can get it like so:

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

这篇关于如何从java获取OS的CPU使用百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆