获取使用率最高 CPU 的进程

Get process with highest CPU usage

我正在尝试编写一个程序来记录 CPU 使用情况和消耗最高 CPU 的进程。假设 firefox.exe 占用最高 CPU 即 70%,它应该只记录这个进程及其 CPU 使用情况。

我正在使用 sigar 库来完成此任务。这是我当前的代码,每秒获取系统 CPU 使用率。

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();
    }

}

如何才能记录最高 CPU 的进程?

IMO 您可以使用以下代码获取所有进程的列表:

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

然后您可以遍历所有进程并获取每个进程的 CPU 用法:

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.
        }

}

然后您可以记录这个 max 值。您还可以查看此 link 以获取一些示例程序。