Skip to content

How to get CPU usage in Linux from Java

May 15, 2009
tags: ,

Technorati Profile

The easiest method to get the CPU usage from a Java class in Linux is to parse the output of the top command. Check out the following code.

import java.io.*;
public class SystemData
{
    static String cmdTop = "top -n 2 -b -d 0.2";
    // returns user cpu usage 
    public static double getCpu()
    {
        double cpu = -1;
        try
        {
            // start up the command in child process
            String cmd = cmdTop;
            Process child = Runtime.getRuntime().exec(cmd);

            // hook up child process output to parent
            InputStream lsOut = child.getInputStream();
            InputStreamReader r = new InputStreamReader(lsOut);
            BufferedReader in = new BufferedReader(r);

            // read the child process' output
            String line;
            int emptyLines = 0;
            while(emptyLines<3)
            {
                line = in.readLine();
                if (line.length()<1) emptyLines++;
            }
            in.readLine();
            in.readLine();
            line = in.readLine();
            System.out.println("Parsing line "+ line);
            String delims = "%";
            String[] parts = line.split(delims);
            System.out.println("Parsing fragment " + parts[0]);
            delims =" ";

            parts = parts[0].split(delims);
            cpu = Double.parseDouble(parts[parts.length-1]);
        }
        catch (Exception e)
        { // exception thrown
            System.out.println("Command failed!");
        }
        return cpu;
    }
}

The parameters from the top command line mean: -b = batch mode, –d 0.2 = take the readings at 0.2 seconds intervals, -n 2 = take 2 readings (the first reading is not correct, from my experience, so we take two).
This code fragment only gets the user CPU percentage. To get the whole CPU percentage, you have to add this value with the system CPU. These values are easy to obtain by changing a few numeric values in the above code. This is left as an exercise for the user. Note that although in general the system CPU and nice CPU percentages are very small, this is not always the case and it is safer to add these values together than to approximate the CPU usage as user CPU only.

Advertisements
2 Comments leave one →
  1. alexandru permalink
    September 23, 2010 2:59 am

    You don’t need to parse top in Linux. You need to parse one of files in /proc filesystem.

  2. andrey permalink
    March 19, 2014 6:57 am

    Does anyone knows what is the max value that method getSystemLoadAverage can return?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: