背景
IntelliJ IDEA
與以下分析工具集成:
-
Async Profiler
:適用于 Linux 和 macOS 的 CPU 和內存分析工具。 -
Java Flight Recorder
:Oracle 提供的 CPU 工具蹦漠,可在 Linux屯蹦、macOS 和 Windows 上使用。
使用簡介
public class Demo {
public static void main(String[] args) {
for (int i = 0; i < 10000000; i++) {
System.out.println(produceString());
}
}
private static String produceString() {
return "Hello World";
}
}
選擇 【Run 'xxx' with 'Java Flight Recorder'
】
會出現如下錯誤:
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Error: To use 'FlightRecorder', first unlock using -XX:+UnlockCommercialFeatures.
在 VM options 中添加 -XX:+UnlockCommercialFeatures
參數。
在【Profiler】窗口點擊【Stop Profiling and Show Results】
然后就可以看到結果阔逼。
Profiler 展示圖表
1. Flame Graph(火焰圖)
2. Call Tree(調用樹)
3. Method List(方法列表)
F4
調轉到源碼:
實戰(zhàn)演練
public class Demo {
@SneakyThrows
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
System.out.println(produceString());
}
System.out.println("準備進入需要測試的方法");
testMethod();
System.out.println("已經從測試的方法返回");
Thread.sleep(10 * 1000);
}
private static String produceString() {
return "Hello World";
}
private static void testMethod() {
int count = 0;
for (int i = 0; i < 30; ++ i) {
timeConsuming();
}
System.out.println(count);
}
@SneakyThrows
private static void timeConsuming(){
for (int i = 0; i < 20000; ++ i) {
byte[] temp = new byte[10000];
new Random().nextBytes(temp);
}
}
}
假設 testMethod()
方法執(zhí)行耗時太長,我們需要排查時間花費在哪里地沮。
排查步驟如下所示:
-
1)在需要排查的方法前后打上斷點(這個方法嗜浮,可能是根據日志中的執(zhí)行時間識別出來的)羡亩,如下圖所示。
2)以 debug 模式啟動項目危融。(需要在 VM options 中添加
-XX:+UnlockCommercialFeatures
參數畏铆。)-
3)在第一個斷點(需要排查的方法前一行語句)暫停時,在 Profiler 創(chuàng)建選擇第(1)步啟動 JVM 進程(
Process Name
一般會展示為 main 函數所在的類)進行Attach Profiler to Process...
的操作专挪。如下圖所示
- 4)繼續(xù)運行之前的項目及志,在第二個斷點暫停時,在【Profiler】窗口點擊【Stop Profiling and Show Results】寨腔,然后繼續(xù)運行之前的項目。
通過【Flame Graph】可以看出率寡,java.util.Random#nextBytes
調用棧的采樣率為 99.43%
迫卢。表示 CPU 大部分時間都在執(zhí)行 java.util.Random#nextBytes
函數。和預期一致冶共!