进程 cpu 时间是您的进程自启动以来使用的 CPU 的总纳秒数。因此,要获得百分比,您将需要 2 条额外的信息:
- CPU 的数量。这可从OperatingSystemMXBean.getAvailableProcessors()或Runtime.availableProcessors()获得。
- 在进程 cpu 时间累积期间经过的相应挂钟时间,最好使用System.nanoTime()完成,因为它提供与进程 cpu 时间相同的“单位”。
实现上述第 2 项的最佳方法是定期轮询进程 cpu 时间,在第一次轮询之后,经过的挂钟时间将是当前System.nanoTime()减去之前轮询中收集的时间时期。
所以现在你有:
- 挂钟经过的时间(这个时间段的时间,减去上一个时间段的时间)调用这个X
- 进程经过的cpu时间(本期的时间,减去上一期的时间)调用这个Y
- CPU 的数量。称它为C
利用率百分比为 Y / (X x C) * 100
这是一个快速而肮脏的 groovy 脚本,它演示了这一点:
import java.lang.management.*;
import java.util.concurrent.*;
osx = ManagementFactory.getOperatingSystemMXBean();
cores = osx.getAvailableProcessors();
// Factorial to keep the process busy so we can see some actual activity
factorial = { n ->
int fact = 1;
int i = 1;
while(i <= n) {
i++;
fact *= i;
}
return fact;
}
long elapsedTime = -1, startTime = -1;
long elapsedCpu = -1, startCpu = -1;;
for(i in 0..20) {
startTime = System.nanoTime();
startCpu = osx.getProcessCpuTime();
CountDownLatch latch = new CountDownLatch(cores);
for(x in 1..cores) {
Thread.startDaemon() {
factorial(1000000);
latch.countDown();
}
}
latch.await();
elapsedTime = System.nanoTime()-startTime;
elapsedCpu = osx.getProcessCpuTime()-startCpu;
percUsage = (elapsedCpu / (elapsedTime* cores)) *100;
println "Percent Usage:$percUsage %";
}
输出:
Percent Usage:51.5167066100 %
Percent Usage:53.5206121100 %
Percent Usage:55.3874037900 %
Percent Usage:59.8187255600 %
Percent Usage:60.0488511300 %
Percent Usage:68.3172332900 %
Percent Usage:45.0529180000 %
Percent Usage:58.3662459200 %
Percent Usage:62.6933609700 %
Percent Usage:60.1530673000 %
Percent Usage:69.0448532600 %
Percent Usage:52.0072152200 %
Percent Usage:57.1837311400 %
Percent Usage:65.8311579500 %
Percent Usage:66.3076807600 %
Percent Usage:69.8803721800 %
Percent Usage:28.5111361300 %
Percent Usage:40.1093035100 %
Percent Usage:60.9499459700 %
Percent Usage:68.7113809300 %
Percent Usage:71.8252480400 %
你可能应该比我做的更好。