I am trying to write a program which logs the CPU usage & the process which is consuming highest CPU. Suppose firefox.exe is taking highest CPU i.e. 70%, it should log only this process with its CPU usage.
I am using sigar library to achive this task. Here is my current code which gets the system CPU usage every second.
public class CPULogger {
private static Sigar sigar = new Sigar();
public void startLogging()
{
Mem mem = null;
CpuTimer cpuTimer = null;
CpuPerc cpuPerc = null;
FileSystemUsage fileSystemUsage = null;
int num = 0;
try
{
System.load(System.getProperty("user.dir") + "\\sigar-x86-winnt.dll");
}
catch(Exception exc)
{
writeLogs(exc.getMessage());
}
while(true)
{
try
{
Thread.sleep(1000);
cpuPerc = sigar.getCpuPerc();
num = (int)Math.ceil(cpuPerc.getCombined()*100);
writeLogs(Double.toString(num).split("\\.")[0] + " %" + (num >= 90 ? "\tAlert" : ""));
}
catch(Exception e)
{
writeLogs(e.getMessage());
}
}
}
public void writeLogs(String logDesc)
{
try
{
PrintWriter writer;
writer = new PrintWriter(new BufferedWriter(new FileWriter("Logs.txt", true)));
writer.println(new java.util.Date() + "\t" + logDesc);
writer.close();
}
catch(IOException e)
{}
catch(Exception e)
{
}
}
public static void main(String[] args) {
CPULogger ul = new CPULogger();
ul.startLogging();
}
}
How can I make it to log the process with highest CPU ?