分析 CPU 時間
你正在最佳化一個進行各種計算的財務分析應用程式。為了精準掌握處理器使用情形,你需要實作一個工具,量測不同操作實際消耗的 CPU 時間,這將幫助你找出哪些計算才是真正的 CPU 密集。
必要的 lang.management 套件已為你匯入。
本練習屬於課程
Java 程式碼最佳化
練習說明
- 從
ManagementFactory類別擷取ThreadMXBean執行個體。 - 取得目前執行緒的 CPU 時間。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Main {
public static long getCpuTimeNano() {
// Retrieve the ThreadMXBean instance
ThreadMXBean threadMXBean = ____.____()
if (threadMXBean.isThreadCpuTimeSupported()) {
threadMXBean.setThreadCpuTimeEnabled(true);
// Return the current thread CPU time
return ____(Thread.currentThread().threadId());
} else {
System.out.println("CPU time measurement not supported");
return 0;
}
}
public static long calculateSum(long n) {
long sum = 0;
for (long i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
public static long calculateSquareSum(long n) {
long sum = 0;
for (long i = 1; i <= n; i++) {
sum += i * i;
}
return sum;
}
public static void main(String[] args) {
long n = 100_000_000; // 100 million
long startSum = getCpuTimeNano();
long sum = calculateSum(n);
long endSum = getCpuTimeNano();
System.out.println("CPU time for sum: " +
((endSum - startSum) / 1_000_000.0) + " ms");
long startSquareSum = getCpuTimeNano();
long squareSum = calculateSquareSum(n);
long endSquareSum = getCpuTimeNano();
System.out.println("CPU time for square sum: " +
((endSquareSum - startSquareSum) / 1_000_000.0) + " ms");
double ratio = (endSquareSum - startSquareSum) / (double)(endSum - startSum);
System.out.println("Square sum takes " + ratio +
" times more CPU time than regular sum");
}
}