Using OperatingSystemMXBean to get CPU usage

前端 未结 1 1890
一个人的身影
一个人的身影 2020-12-16 14:24

I\'m trying to use Java to get the percentage of CPU used by the currently running Java Virtual Machine. My research has pointed me to using the com.sun.management.Ope

相关标签:
1条回答
  • 2020-12-16 14:49

    Just answering my own question in case it could help somebody.

    What I was doing was technically correct, however I was not giving the OperatingSystemMXBean enough time to gather CPU usage information. The JVM must actually be running for a few seconds before it can gather CPU usage information, and then the refresh resolution is implementation-dependent it would seem.

    Running the code with the following change will start to produce usage information after ~2 seconds on my machine:

    public static void main(String[] args) {
        OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
                .getOperatingSystemMXBean();
    
        while (true) {
            System.out.println(bean.getProcessCpuLoad());
            System.out.println(bean.getSystemCpuLoad());
        }
    
    }
    

    Hopefully this can help somebody

    0 讨论(0)
提交回复
热议问题