我正在尝试编写一个记录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记录进程?
答案 0 :(得分: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以获取一些示例程序。