`在Java中监控每个线程的CPU使用率? [英] `Monitor cpu usage per thread in java?
本文介绍了`在Java中监控每个线程的CPU使用率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想问一下是否有一些简单的方法来确定java
中每个线程的cpu usage
.谢谢
解决方案
我相信 JConsole (已存档的链接)确实通过插件提供了此类信息
>
它使用 ThreadMXBean getThreadCpuTime()函数. /p>
类似的东西:
long upTime = runtimeProxy.getUptime();
List<Long> threadCpuTime = new ArrayList<Long>();
for (int i = 0; i < threadIds.size(); i++) {
long threadId = threadIds.get(i);
if (threadId != -1) {
threadCpuTime.add(threadProxy.getThreadCpuTime(threadId));
} else {
threadCpuTime.add(0L);
}
}
int nCPUs = osProxy.getAvailableProcessors();
List<Float> cpuUsageList = new ArrayList<Float>();
if (prevUpTime > 0L && upTime > prevUpTime) {
// elapsedTime is in ms
long elapsedTime = upTime - prevUpTime;
for (int i = 0; i < threadIds.size(); i++) {
// elapsedCpu is in ns
long elapsedCpu = threadCpuTime.get(i) - prevThreadCpuTime.get(i);
// cpuUsage could go higher than 100% because elapsedTime
// and elapsedCpu are not fetched simultaneously. Limit to
// 99% to avoid Chart showing a scale from 0% to 200%.
float cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 1000000F * nCPUs));
cpuUsageList.add(cpuUsage);
}
}
I would like to ask whether there is some simple way to determine cpu usage
per thread in java
. Thanks
解决方案
I believe the JConsole (archived link) does provide this kind of information through a plugin
It uses ThreadMXBean getThreadCpuTime() function.
Something along the line of:
long upTime = runtimeProxy.getUptime();
List<Long> threadCpuTime = new ArrayList<Long>();
for (int i = 0; i < threadIds.size(); i++) {
long threadId = threadIds.get(i);
if (threadId != -1) {
threadCpuTime.add(threadProxy.getThreadCpuTime(threadId));
} else {
threadCpuTime.add(0L);
}
}
int nCPUs = osProxy.getAvailableProcessors();
List<Float> cpuUsageList = new ArrayList<Float>();
if (prevUpTime > 0L && upTime > prevUpTime) {
// elapsedTime is in ms
long elapsedTime = upTime - prevUpTime;
for (int i = 0; i < threadIds.size(); i++) {
// elapsedCpu is in ns
long elapsedCpu = threadCpuTime.get(i) - prevThreadCpuTime.get(i);
// cpuUsage could go higher than 100% because elapsedTime
// and elapsedCpu are not fetched simultaneously. Limit to
// 99% to avoid Chart showing a scale from 0% to 200%.
float cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 1000000F * nCPUs));
cpuUsageList.add(cpuUsage);
}
}
这篇关于`在Java中监控每个线程的CPU使用率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文