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.
How to get CPU usage in Linux from Java
Related Posts:
How to Extract rar files in LinuxRAR is a proprietary compression format widely used today. It’s supposedly has 30% higher compression rate when compared with WinZip. If you download … Read More
Howto Create .ISO images from CD or DVD in Linux In Linux computer, we have a simple tool to create CD or DVD .ISO file. This is very helpfull to backup your CD and DVD into ISO images: T… Read More
How to Create and Extract RAR Files in LinuxI've been sharing mp3s with my close friends for years. We share mp3 files within our same interest in music. As I'm now a total Linux desktop user (I… Read More
How to Install rar and unrar programs in Linux or UnixHowever, I am a linux supporter and I don't want to make you upset while bumping into this blog and didn't really get what you need. So, here is how t… Read More
How to Open, Extract and Convert DAA, ISO and BIN Files in Linux with Free PowerISO for LinuxPowerISO provides a free PowerISO for Linux utility which can extract, list, and convert image files in Linux. The image file formats supported by the… Read More
0 comments:
Post a Comment