You want to know the CPU usage during Java programming so that you can decide whether to load the task. First with Google search, Windows environment can use JNI through the API function Getprocesscputime () to get, and someone gave the source code. Linux seems to have no one to give the source code, so decided to write one, after practice, and finally succeeded, is to post code, and share with you.
Thinking as follows: The Linux system can use the top command to see the process using CPU and memory, through the runtime class exec () method system command "Top", get "top" output, so that CPU and memory usage. A little change to this program, you can also get the use of memory.
Package com.hmw.test;
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
/**
* @author WANLH
* @version 1.0
*/
public class CPUUsage {
Public double Getcpuusage () throws Exception {
Double cpuused = 0;
Runtime RT = Runtime.getruntime ();
Process p = rt.exec ("Top-b-N 1");//Call the system's "top" command
BufferedReader in = null;
try {
in = new BufferedReader (New InputStreamReader (P.getinputstream ()));
String str = NULL;
string[] Strarray = null;
while (str = In.readline ())!= null) {
int m = 0;
if (Str.indexof ("R")!=-1 && str.indexof ("top") = = 1) {//profiling the running process except the top process itself
Strarray = Str.split ("");
for (String Tmp:strarray) {
if (Tmp.trim (). Length () = 0)
Continue
if (++m = 9) {//9th column% of CPU usage (RedHat 9)
cpuused + = double.parsedouble (TMP);
}
}
}
}
catch (Exception e) {
E.printstacktrace ();
finally {
In.close ();
}
return cpuused;
}
public static void Main (string[] args) throws Exception {
CPUUsage CPU = new CPUUsage ();
SYSTEM.OUT.PRINTLN ("CPU used:" + cpu.getcpuusage () + "%");
}
}
Source: http://www.itpub.net/archiver/tid-859283.html