Java get CPU usage

Recently, we made a Java performance statistics problem. We need to count the CPU usage of the current process. At first, we used Java MxBean to get
OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
double cpu = osMxBean.getSystemLoadAverage();
However, the total system load obtained by this method can not reflect the CPU usage of the process. Then, a new method is used to count the CPU usage of threads. The specific code is as follows:

package com.service.article;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;

public class CPUMonitorCalc {

    private static CPUMonitorCalc instance = new CPUMonitorCalc();

    private OperatingSystemMXBean osMxBean;
    private ThreadMXBean threadBean;
    private long preTime = System.nanoTime();
    private long preUsedTime = 0;

    private CPUMonitorCalc() {
        osMxBean = ManagementFactory.getOperatingSystemMXBean();
        threadBean = ManagementFactory.getThreadMXBean();
    }

    public static CPUMonitorCalc getInstance() {
        return instance;
    }

    public double getProcessCpu() {
        long totalTime = 0;
        for (long id : threadBean.getAllThreadIds()) {
            totalTime += threadBean.getThreadCpuTime(id);
        }
        long curtime = System.nanoTime();
        long usedTime = totalTime - preUsedTime;
        long totalPassedTime = curtime - preTime;
        preTime = curtime;
        preUsedTime = totalTime;
        return (((double) usedTime) / totalPassedTime / osMxBean.getAvailableProcessors()) * 100;
    }
}

Test method:

package com.service.article;

public class ArticleApplication {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                while (true) {
                    long bac = 1000000;
                    bac = bac >> 1;
                }
            }).start();;
        }
        while (true) {
            Thread.sleep(5000);
            System.out.println(CPUMonitorCalc.getInstance().getProcessCpu());
        }
        
    }
}

The test results are almost the same as those calculated by the operating system

Tags: Java

Posted on Sun, 03 May 2020 06:11:50 -0700 by techmeister