在Windows机器上使用Java管理API正确计算CPU使用率
我想实现一个测试程序,正确地使用Java管理API计算CPU使用率。结果应该是所有处理器及其核心的算术平均值。windows机器上的问题是标准方法
ManagementFactory.getOperatingSystemMXBean().
(a) getSystemLoadAverage()
(b) getProcessCpuLoad()
(c) getSystemCpuLoad()
过于频繁地传递值-1.00,这意味着无法计算cpu使用率。这些标准方法在linux上运行良好,但在windows上不起作用。我还在这个论坛上寻找解决方案。我在这个论坛上找到了一些解决这个问题的方法,但没有一个对我有帮助。例如,下面的代码总是在我的机器上计算16%,这是不现实的
public synchronized double getCpuUsage() {
double cpuPercent = 0.0;
for (int i = 0; i < 30; i++) {
long start = System.nanoTime();
int cpuCount = getOperatingSystemMxBean().getAvailableProcessors();
Random random = new Random(start);
int seed = Math.abs(random.nextInt());
int primes = 10000;
long startCpuTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
start = System.nanoTime();
while (primes != 0) {
if (isPrime(seed))
{
primes--;
}
seed++;
}
cpuPercent = calcCpu(startCpuTime, start, cpuCount);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return cpuPercent;
}
static boolean isPrime(int n) {
// 2 is the smallest prime
if (n <= 2)
{
return n == 2;
}
// even numbers other than 2 are not prime
if (n % 2 == 0) {
return false;
}
//check odd divisory from 3
// to the square root of n
for (int i = 3, end = (int)Math.sqrt(n); i <= end; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int calcCpu(long cpuStartTime, long elapsedStartTime, int cpuCount) {
long end = System.nanoTime();
long totalAvailCpuTime = cpuCount * (end - elapsedStartTime);
long totalUsedCpuTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime() - cpuStartTime;
float per = ((float)totalUsedCpuTime*100) / (float)totalAvailCpuTime;
//log (per);
return (int)per;
}
private OperatingSystemMXBean getOperatingSystemMxBean() {
return (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
}
你知道解决这个问题的正确方法吗
# 1 楼答案
我通过使用oshi库在windows机器上解决了这个问题。在Solaris和Linux上,我继续使用Java管理API