Hi all,
I want to do a CPU monitoring program and for that I need the CPU usage per second.
How do i determine the CPU usage using Java ???
Please give any suggestions as to how to go about this???
OS i am using is Linux.
Thanks in advance
Printable View
Hi all,
I want to do a CPU monitoring program and for that I need the CPU usage per second.
How do i determine the CPU usage using Java ???
Please give any suggestions as to how to go about this???
OS i am using is Linux.
Thanks in advance
Profiling CPU usage from within a Java application - Java World
google:java cpu usage
There is a way using pure java. It may take some adapting to fit your needs. The monitoring could be placed on it's own thread and have a handle to the thread you wish to monitor.
cpuperc in this case holds the aprox. cpu usage %. It is fairly accurate. You could average several to get a better idea.
Code:
//import java.lang.management.*;
ThreadMXBean TMB = ManagementFactory.getThreadMXBean();
long time = new Date().getTime() * 1000000;
long cput = 0;
double cpuperc = -1;
//Begin loop.
if( TMB.isThreadCpuTimeSupported() )
{
if(new Date().getTime() * 1000000 - time > 1000000000) //Reset once per second
{
time = new Date().getTime() * 1000000;
cput = TMB.getCurrentThreadCpuTime();
}
if(!TMB.isThreadCpuTimeEnabled())
{
TMB.setThreadCpuTimeEnabled(true);
}
if(new Date().getTime() * 1000000 - time != 0)
cpuperc = (TMB.getCurrentThreadCpuTime() - cput) / (new Date().getTime() * 1000000.0 - time) * 100.0;
}
else
{
cpuperc = -2;
}
//Do cpu intensive stuff
//End Loop
search for javasysmon on github. It's BSD licensed. Support for Windows, Mac OS X and Linux (so far)
hi... i m also working in java... i wanna retrieve the same cpu usage(for system not for the jvm running) using java code... i cannot understand the code given above..
i can execute and get output for the given code. but even if i use loop and execute the loop once for 5 seconds also the function is not resetting the values. i m getting the same output for how many times i m running the loop...
also i could not get what does the cpuperc value is??? like i want the result in percentage... and in what unit the result comes??? how can i check whether the value i m getting is correct??? pls give any suggestions...
Best to ask your new question in its own thread -- you'll stand a much better chance of getting a viable answer this way. So I'm going to lock this thread but invite you to post your own question with as much detail as is necessary to answer your question. Feel free to link to this thread.