Java obtains Linux CPU and memory usage by calling the top command __linux

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.