我试图通过Java程序找到一些系统统计信息(CPU利用率%,磁盘利用率%和内存利用率%)。为此我一直在使用SIGAR。虽然(我认为)我得到后两个正确,但我没有得到CPU利用率%正确。在下面添加我的代码,有人可以帮我理解这里出了什么问题吗?
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import org.hyperic.sigar.CpuTimer;
import org.hyperic.sigar.DiskUsage;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class SystemMonitor {
private static Sigar sigar = new Sigar();
public static void getSystemStatistics(){
Mem mem = null;
CpuTimer cputimer = null;
FileSystemUsage filesystemusage = null;
try {
mem = sigar.getMem();
cputimer = new CpuTimer(sigar);
filesystemusage = sigar.getFileSystemUsage("C:");
} catch (SigarException se) {
se.printStackTrace();
}
System.out.print(mem.getUsedPercent()+"\t");
System.out.print(cputimer.getCpuUsage()+"\t");
System.out.print(filesystemusage.getUsePercent()+"\n");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SystemMonitor m1 = new SystemMonitor();
for(int i=0; i<1000;i++){
m1.getSystemStatistics();
}
}
}
我持续获得CPUUtilisation%0,我认为这是不正确的。
答案 0 :(得分:3)
我错误地解释了CpuTimer。我可以通过使用CpuPerc来找到CPU利用率。附加代码段:
public static void getSystemStatistics(){
Mem mem = null;
CpuPerc cpuperc = null;
FileSystemUsage filesystemusage = null;
try {
mem = sigar.getMem();
cpuperc = sigar.getCpuPerc();
filesystemusage = sigar.getFileSystemUsage("C:");
} catch (SigarException se) {
se.printStackTrace();
}
System.out.print(mem.getUsedPercent()+"\t");
System.out.print((cpuperc.getCombined()*100)+"\t");
System.out.print(filesystemusage.getUsePercent()+"\n");
}
答案 1 :(得分:1)
我刚刚写了这样的东西,它很有效,你可以查看它并找到你的代码所需要的东西。注意:别忘了启动线程^^
thread = new Thread(new Runnable() {
public void run() {
while (true) {
/*
* Memory of System
*/
long actualFree = mem.getActualFree() / 1024
/ 1024;
long actualUsed = mem.getActualUsed() / 1024
/ 1024;
long per1Mem = (actualFree + actualUsed) / 100;
system.out.println((((int) actualFree / per1Mem) * 1.0) / 100);
/*
* Disk Space
*/
File file = new File("/");
long totalSpace = file.getTotalSpace() / 1024 / 1024;
long freeSpace = file.getUsableSpace() / 1024 / 1024;
long per1Disk = totalSpace / 100;
system.out.println(((int) freeSpace / per1Disk) * 1.0) / 100);
/*
* CPU USAGE
*/
try {
thread.sleep(1000); //needed for finding proper cpu usage
CpuPerc perc = sigar.getCpuPerc();
system.out.println(perc.getCombined());
} catch (SigarException | InterruptedException e) {
System.out.println("SigarException in CPU or InterruptedException!");
}
}
}
});