jconsole CPU Usage Jmx

打开JConsole可看到CPU Usage这一项,但是它指的是JVM的使用CPU,MBean里面是没有提供这一项的,怎么得到?

使用如下代码:

long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();

// for the sake of the example do some
// CPU consuming task here - e.g.
// use BigInteger and Math.sqrt()
//
BigInteger acc = new BigInteger("0");
final int max = 1000000;
for (long i=0; i<max; i++) {     final double d = Double.parseDouble("1"+i);     final double sq = Math.sqrt(d);     final BigInteger b = new BigInteger(""+(long)sq);     acc = acc.add(b);
}

long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();

long percent;
if (nanoAfter > nanoBefore)     percent = ((cpuAfter-cpuBefore)\*100L)/    (nanoAfter-nanoBefore);
else percent = 0;

System.out.println("Cpu usage: "+percent+"%");

其实这个是不太准的,各平台nanoTime实现不一样,结果可能会让人莫名其妙!


Total views.

© 2013 - 2024. All rights reserved.

Powered by Hydejack v6.6.1