Take CPU usage in percentage

Asked

Viewed 238 times

-1

How to take CPU usage in percentage in java?

The closest I got was this code I tried to adapt, but it presents different results with respect to the Windows task manager

goes below

package teste;

import java.io.File;
 import java.lang.management.ManagementFactory;
// import java.lang.management.Operating

    SystemMXBean;
     import java.lang.reflect.Method;
     import java.lang.reflect.Modifier;
     import java.lang.management.RuntimeMXBean;
     import java.io.*;
     import java.net.*;
     import java.util.*;
     import java.io.LineNumberReader;
     import java.lang.management.ManagementFactory;
    import com.sun.management.OperatingSystemMXBean;
    import java.lang.management.ManagementFactory;
    import java.util.Random;

    public class Teste {

        public static void printUsage(Runtime runtime)
         {
         long total, free, used;
         int mb = 1024*1024;

         total = runtime.totalMemory();
         free = runtime.freeMemory();
         used = total - free;
         System.out.println("\nTotal Memory: " + total / mb + "MB");
         System.out.println(" Memory Used: " + used / mb + "MB");
         System.out.println(" Memory Free: " + free / mb + "MB");
         System.out.println("Percent Used: " + ((double)used/(double)total)*100 + "%");
         System.out.println("Percent Free: " + ((double)free/(double)total)*100 + "%");
        }
        public static void log(Object message)
             {
                System.out.println(message);
             }

            public static int calcCPU(long cpuStartTime, long elapsedStartTime, int cpuCount)
            {
                 long end = System.nanoTime();
                 long totalAvailCPUTime = cpuCount * (end-elapsedStartTime);
                 long totalUsedCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime()-cpuStartTime;
                 //log("Total CPU Time:" + totalUsedCPUTime + " ns.");
                 //log("Total Avail CPU Time:" + totalAvailCPUTime + " ns.");
                 float per = ((float)totalUsedCPUTime*100)/(float)totalAvailCPUTime;
                 log( per);
                 return (int)per;
            }

            static boolean isPrime(int n)
            {
         // 2 is the smallest prime
                if (n <= 2)
                {
                    return n == 2;
                }
         // even numbers other than 2 are not prime
                if (n % 2 == 0)
                {
                    return false;
                }
         // check odd divisors from 3
         // to the square root of n
             for (int i = 3, end = (int)Math.sqrt(n); i <= end; i += 2)
             {
                if (n % i == 0)
             {
             return false;
            }
            }
     return true;
    }
        public static void main(String [] args)
        {
                int mb = 1024*1024;
                int gb = 1024*1024*1024;
                 /* PHYSICAL MEMORY USAGE */
                 System.out.println("\n**** Sizes in Mega Bytes ****\n");
                com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
                //RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
                //operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
                com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)
                java.lang.management.ManagementFactory.getOperatingSystemMXBean();
                long physicalMemorySize = os.getTotalPhysicalMemorySize();
                System.out.println("PHYSICAL MEMORY DETAILS \n");
                System.out.println("total physical memory : " + physicalMemorySize / mb + "MB ");
                long physicalfreeMemorySize = os.getFreePhysicalMemorySize();
                System.out.println("total free physical memory : " + physicalfreeMemorySize / mb + "MB");
                /* DISC SPACE DETAILS */
                File diskPartition = new File("C:");
                File diskPartition1 = new File("D:");
                File diskPartition2 = new File("E:");
                long totalCapacity = diskPartition.getTotalSpace() / gb;
                long totalCapacity1 = diskPartition1.getTotalSpace() / gb;
                double freePartitionSpace = diskPartition.getFreeSpace() / gb;
                double freePartitionSpace1 = diskPartition1.getFreeSpace() / gb;
                double freePartitionSpace2 = diskPartition2.getFreeSpace() / gb;
                double usablePatitionSpace = diskPartition.getUsableSpace() / gb;
                System.out.println("\n**** Sizes in Giga Bytes ****\n");
                System.out.println("DISC SPACE DETAILS \n");
                //System.out.println("Total C partition size : " + totalCapacity + "GB");
                //System.out.println("Usable Space : " + usablePatitionSpace + "GB");
                System.out.println("Free Space in drive C: : " + freePartitionSpace + "GB");
                System.out.println("Free Space in drive D:  : " + freePartitionSpace1 + "GB");
                System.out.println("Free Space in drive E: " + freePartitionSpace2 + "GB");
                if(freePartitionSpace <= totalCapacity%10 || freePartitionSpace1 <= totalCapacity1%10)
                {
                    System.out.println(" !!!alert!!!!");
                }
                else
                    System.out.println("no alert");

                Runtime runtime;
                byte[] bytes;
                System.out.println("\n \n**MEMORY DETAILS  ** \n");
                // Print initial memory usage.
                runtime = Runtime.getRuntime();
                printUsage(runtime);

                // Allocate a 1 Megabyte and print memory usage
                bytes = new byte[1024*1024];
                printUsage(runtime);

                bytes = null;
                // Invoke garbage collector to reclaim the allocated memory.
                runtime.gc();

                // Wait 5 seconds to give garbage collector a chance to run
                try {
                Thread.sleep(5000);
                } catch(InterruptedException e) {
                e.printStackTrace();
                return;
                }

                // Total memory will probably be the same as the second printUsage call,
                // but the free memory should be about 1 Megabyte larger if garbage
                // collection kicked in.
                printUsage(runtime);
                for(int i = 0; i < 30; i++)
                         {
                             long start = System.nanoTime();
                            // log(start);
                            //number of available processors;
                             int cpuCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
                             Random random = new Random(start);
                             int seed = Math.abs(random.nextInt());
                             log("\n \n CPU USAGE DETAILS \n\n");
                             log("Starting Test with " + cpuCount + " CPUs and random number:" + seed);
                             int primes = 10000;
                             //
                             long startCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
                             start = System.nanoTime();
                             while(primes != 0)
                             {
                                if(isPrime(seed))
                                {
                                    primes--;
                                }
                                seed++;

                            }
                             float cpuPercent = calcCPU(startCPUTime, start, cpuCount);
                             log("CPU USAGE : " + cpuPercent + " % ");


                             try
                             {
                                 Thread.sleep(1000);
                             }
                             catch (InterruptedException e) {}
            }

                try
                {
                    Thread.sleep(500);
                } 
                catch (Exception ignored) { }
            }
    }

1 answer

0


Your variable os contains a com.sun.management.OperatingSystemMXBean. This class offers a method getSystemCpuLoad() that returns a double between 0 and 1 indicating CPU usage or then -1 if it fails to measure CPU usage. Multiply this value from 0 to 1 per 100, and it will have a value in percentage.

The total memory value you should get from OperatingSystemMXBean. The value given by the class Runtime refers only to the JVM memory.

The code you have has a while to test if a lot of random numbers are primes and thus try to keep the CPU busy to then measure CPU usage. It also means that (1) it would be messy with any measurement of CPU consumption you set out to do, (2) that any measurement made would be artificial and would not correspond to what happens in your system and (3) that the code as it was was was useless to measureif actual CPU consumption in a real situation where you need it. In addition, the method calcCPU proposes to make a home and incorrect implementation of CPU consumption measurement.

I deleted from your code all this primes generating stuff and also the method calcCPU, delegating only to the OperatingSystemMXBean measurements. I also tweaked and rearranged the code as a whole. It looked like this:

package teste;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.text.NumberFormat;
import java.util.Locale;

public class Teste {

    private static final long KB = 1024;
    private static final long MB = 1024 * KB;
    private static final long GB = 1024 * MB;
    private static final long TB = 1024 * GB;
    private static final com.sun.management.OperatingSystemMXBean OS_BEAN =
            (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    public static void log(Object message) {
        System.out.println(message);
    }

    private static void sleep1Sec() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore.
        }
    }

    private static String formatDouble(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance(new Locale("PT", "BR"));
        nf.setMaximumFractionDigits(2);
        return nf.format(d);
    }

    private static String formatBytes(long b) {
        return b >= TB ? formatDouble(b / (double) TB) + " TB"
                : b >= GB ? formatDouble(b / (double) GB) + " GB"
                : b >= MB ? formatDouble(b / (double) MB) + " MB"
                : b >= KB ? formatDouble(b / (double) KB) + " KB"
                : b + " bytes";
    }

    public static void printMemoryUsage() {
        //Runtime r = Runtime.getRuntime();
        //long jvmTotal = r.totalMemory();
        //long jvmFree = r.freeMemory();
        //long jvmUsed = jvmTotal - jvmFree;
        long total = OS_BEAN.getTotalPhysicalMemorySize();
        long free = OS_BEAN.getFreePhysicalMemorySize();
        long used = total - free;
        System.out.println("Total Memory: " + formatBytes(total));
        System.out.println("Memory Used: " + formatBytes(used));
        System.out.println("Memory Free: " + formatBytes(free));
        System.out.println("Percent Used: " + formatDouble(100 * used / (double) total) + "%");
        System.out.println("Percent Free: " + formatDouble(100 * free / (double) total) + "%");
    }

    public static void printDiskUsage(String disk) {
        File diskPartition = new File(disk + ":");
        long total = diskPartition.getTotalSpace();
        long free = diskPartition.getFreeSpace();
        long usable = diskPartition.getUsableSpace();
        System.out.println("Total space in drive " + disk + ": " + formatBytes(total));
        System.out.println("Free space in drive " + disk + ": " + formatBytes(free));
        System.out.println("Usable space in drive " + disk + ": " + formatBytes(usable));
    }

    public static void printDiskUsage(String... disks) {
        for (String disk : disks) {
            printDiskUsage(disk);
        }
    }

    public static void printProcessorUsage() {
        int cpuCount = OS_BEAN.getAvailableProcessors();
        double load = OS_BEAN.getSystemCpuLoad();
        String formattedLoad = load >= 0 ? formatDouble(load * 100) + "%" : "unknown";
        log("With " + cpuCount + " CPUs usage is " + formattedLoad + ".");
    }

    public static void main(String[] args) {
        printMemoryUsage();
        printDiskUsage("C", "D", "E");

        for (int i = 0; i < 30; i++) {
            printProcessorUsage();
            sleep1Sec();
        }
    }
}

The above code works for me, but to be honest, it does not provide an equal number to the measurement made by Windows, although surely the numbers are similar within some reasonable margin of error.

  • Man, fantastic understood a lot more than in 3 weeks of research, I really don’t know how to thank you. Thank you even for helping I hope one day to have half the knowledge you have. It’s people like you who help others that make the world better. Thanks again my friend

  • @Sáviosantos If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.