|
想得到针对每一个进程的占CPU的百分比,但是用getpercent()这个打印出来老是0.0。上网搜了好久也没有搜到用java写的得到单个进程占CPU百分比的例子。第一次接触这些东西所以懂得不多,求帮助T_T……最后再次谢谢!还有如果有数据了值也对不上。sleep有加,但也是没多大效果。 Sigar sigar = new Sigar(); long pid = sigar.getPid(); int sleep_time = 100; SigarProxy sigars = SigarProxyCache.newInstance(sigar, sleep_time); ProcCpu cpuu; try { ProcCpu cpu = sigars.getProcCpu(pid); cpu.getPercent(); //it return 0.0 first Thread.sleep(sleep_time); cpuu = sigar.getProcCpu(pid); System.out.println(cpuu.getPercent()); } catch (Exception e) { e.printStackTrace(); } |
|
![]() 20分 |
public static void main(String[] args) throws SigarException {
final Random rand = new Random();
new Thread() {
public void run() {
while(true) {
if(rand.nextBoolean()) {
for (int i = 0, l = 10000000; i < l; i++) {
rand.nextDouble();
}
} else {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
NumberFormat format = new DecimalFormat("0");
Sigar sigar = new Sigar();
long pid = sigar.getPid(); //javaw的pid 或者注释掉上边的Thread,在资源管理器看pid
int availableProcessors = Runtime.getRuntime().availableProcessors();
while (true) {
System.out.println(format.format(sigar.getProcCpu(pid).getPercent() / availableProcessors * 100) + ""%"");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
![]() |
你给的方案可行。但是有一个问题请教,就是里面的数据貌似有时候不稳定,有时候CPU使用率会超过100%,比如1000%,请问这是什么原因的导致的? |
![]() |
1000%没遇到过啊,我测的最多就100% |
![]() |
还有一个问题噢,sigar.getProcCpu(pid).getPercent() ;如果再输出一遍。貌似数据不对,几乎都是0。 |

