2015-10-20 54 views
0

我正在嘗試編寫一個程序,它記錄CPU使用率爲&的進程消耗最高CPU。假設firefox.exe佔用的CPU最高,即70%,它應該只記錄這個進程的CPU使用率。獲取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記錄進程?

回答

1

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一些示例程序。

+0

'sigar.getProcCpu(processId);'沒有顯示正確的CPU利用率。即使某些過程達到5-10,它總是顯示小於零。 –

+0

選中此項:http://stackoverflow.com/questions/19323364/using-sigar-api-to-get-jvm-cpu-usage –