Get process with highest CPU usage

2019-09-04 23:48发布

问题:

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 ?

回答1:

IMO you can use the following code to get list of all processes:

    final Sigar sigar = new Sigar();        
    final long[] processes;
    try {
        processes = sigar.getProcList();
    } catch (Exception e) {
        //throw exception.
    }

Then you can iterate over all the processes and get the CPU usage for each process:

for (final long processId : processes)  {
        try {
            ProcCpu procCpu = sigar.getProcCpu(processId);
            // compare and set max value.
        } catch (SigarException e) {
            //In case for some pid access is denied.
        }

}

Then you can log this max value. You can also check this link for some sample programs.



标签: java sigar