The following java program uses the linux command 'mpstat' to determine the CPU load .
To see the client-server version of the program with multiple clients, see here .
public class CpuLoad {
public static void main(String args[]) {
int i=1;
float finalres;
try{
// execute the linux command
Process p=Runtime.getRuntime().exec("mpstat");
BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
//read the row corresponding to cpu idle
while((line=in.readLine())!=null && i<4){
i++;
}
String res=line.substring(line.length()-5);
finalres=Float.parseFloat(res);
//convert the idle to cpuload
System.out.println("CPU load:"+(100-finalres)+"%");
}
catch(Exception e){
System.out.println(e);
}
}
}
To see the client-server version of the program with multiple clients, see here .
public class CpuLoad {
public static void main(String args[]) {
int i=1;
float finalres;
try{
// execute the linux command
Process p=Runtime.getRuntime().exec("mpstat");
BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
//read the row corresponding to cpu idle
while((line=in.readLine())!=null && i<4){
i++;
}
String res=line.substring(line.length()-5);
finalres=Float.parseFloat(res);
//convert the idle to cpuload
System.out.println("CPU load:"+(100-finalres)+"%");
}
catch(Exception e){
System.out.println(e);
}
}
}
No comments:
Post a Comment