Get process with highest CPU usage

淺唱寂寞╮ 提交于 2020-01-17 12:40:19

问题


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.



来源:https://stackoverflow.com/questions/33227718/get-process-with-highest-cpu-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!