I'm using Sigar to get the CPU usage of the current running JVM in an application server and store it for historical view of this data, but I always get 0% CPU percentage.
In the meanwhile, I keep my visualVM open to monitor CPU usage, and I get to see the CPU % changing periodically in visualVM while it always reports 0% using Sigar.
Here is the code I m running periodically:
Sigar sigar = new Sigar();
ProcCpu cpu = null;
long pId = sigar.getPid(); // This one gives me the same process ID that I see in visualVM
try {
cpu = sigar.getProcCpu(pId);
}
catch (SigarException se) {
se.printStackTrace();
}
System.out.print(cpu.getPercent());
This code always gives 0%.
What am I doing wrong it this case? How can I get Sigar to display CPU usage similar to the usage displayed in VisualVM?
I tried adding
cpu.gather(sigar, pId);
after calling getProcCpu(pid), but I keep getting only two values (0.0 and 9.08729312E-315) even if I keep increasing and decreasing load on the server...
I think that it depends on how Sigar interprets available information. Information available to it (CPU usage time) updates not very often, and
ProcCpu
is just an instant process CPU usage information, that is why CPU usage for mostProcCpu
is 0. Never seen them, but for someProcCpu
this value should be be vastly superior to 100%.You could get CPU usage for some period, analysing two
ProcCpu
s from the start and the end moments of it, taking CPU usage time and time ofProcCpu
(lastTime) into account. But remember, that CPU usage time value updates not very often, so it is possible to get the same CPU usage time forProcCpu
s more than second apart. To have actual CPU usage information, you have to collect two or moreProcCpu
s.I'v sketched a monitor that aggregates and updates information on CPU usage:
ProcCpu
— instant CPU usage by process informationcurPc.getTotal()
— total time that process used CPUcurPc.getLastTime()
— moment for whichProcCpu
represents informationload
) is a ratio of time that process used CPU during some period (totalDelta
) and this period's duration (timeDelta
).While CPU usage time updates not very often, I've introdused simple heuristic, that supposes that the load is the same as previous, while CPU usage time doesn't update. But supposing that it could be zero load for a process for some time, I've introdused a duration (
TOTAL_TIME_UPDATE_LIMIT
), after which the same CPU usage time value become legal, and it is supposed that the load is really zero.