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.

5 Comments leave one →
  1. Jozef Hovan permalink
    July 14, 2009 11:15 am

    Isn’t it better? Or it returns different values?

    public static double getCpu()
    {
    OperatingSystemMXBean osBean=ManagementFactory.getOperatingSystemMXBean();
    return osBean.getSystemLoadAverage();
    }

    • Dragos permalink*
      July 14, 2009 11:17 am

      The values will be different. Your method returns an average of the CPU load, not the CPU load at the time of the call.

  2. 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.

    • Dragos permalink*
      February 10, 2011 10:10 am

      Yup, that is another method. I found this one simpler, but it probably has more overhead.

  3. Nick Zeeb permalink
    February 10, 2011 10:01 am

    the reason you need two readings seems to be explainable from the man pages:

    %CPU — CPU usage
    The task’s share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time.

    hence you can use the -d flag to set your sampling period

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.