Phân tích thời gian CPU
Bạn đang tối ưu hóa một ứng dụng phân tích tài chính thực hiện nhiều phép tính. Để hiểu chính xác mức sử dụng bộ xử lý, bạn cần triển khai một tiện ích đo thời gian CPU chính xác mà các thao tác khác nhau tiêu tốn, từ đó giúp bạn xác định phép tính nào thực sự ngốn CPU.
Các gói lang.management cần thiết đã được nhập sẵn cho bạn.
Bài tập này là một phần của khóa học
Tối ưu hóa mã trong Java
Hướng dẫn bài tập
- Lấy thể hiện
ThreadMXBeantừ lớpManagementFactory. - Lấy thời gian CPU cho luồng hiện tại.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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");
}
}