How to get CPU usage in Linux from Java
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.
Isn’t it better? Or it returns different values?
public static double getCpu()
{
OperatingSystemMXBean osBean=ManagementFactory.getOperatingSystemMXBean();
return osBean.getSystemLoadAverage();
}
The values will be different. Your method returns an average of the CPU load, not the CPU load at the time of the call.
You don’t need to parse top in Linux. You need to parse one of files in /proc filesystem.
Yup, that is another method. I found this one simpler, but it probably has more overhead.
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