CPU分析篇
CPU 性能分析的主要目的是统计函数的调用情况及执行时间,或者更简单的情况就是统计应用程序的 CPU 使用情况。
没有程序运行时的 CPU 使用情况如下图:

运行一段 占用CPU 的小程序,代码如下
package jvisualVM;
public class MemoryCpuTest {
public static void main(String[] args) throws InterruptedException {
cpuFix();
}
/**
* cpu 运行固定百分比
*
* @throws InterruptedException
*/
public static void cpuFix() throws InterruptedException {
// 80%的占有率
int busyTime = 8;
// 20%的占有率
int idelTime = 2;
// 开始时间
long startTime = 0;
while (true) {
// 开始时间
startTime = System.currentTimeMillis();
/*
* 运行时间
*/
while (System.currentTimeMillis() - startTime < busyTime) {
;
}
// 休息时间
Thread.sleep(idelTime);
}
}
}
查看监视页面 Monitor tab

过高的 CPU 使用率可能是由于我们的项目中存在低效的代码;
在我们对程序施压的时候,过低的 CPU 使用率也有可能是程序的问题。
点击取样器Sampler, 点击“CPU”按钮, 启动CPU性能分析会话,VisualVM 会检测应用程序所有的被调用的方法,
在CPU samples tab 下可以看到我们的方法cpufix() 的自用时间最长, 如下图:

切换到Thread CPU Time 页面下,我们的 main 函数这个进程 占用CPU时间最长, 如下图:



浙公网安备 33010602011771号