开始使用免费开始使用

分析 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");
    }
}
编辑并运行代码