Analisando o tempo de CPU
Você está otimizando um aplicativo de análise financeira que realiza cálculos. Para entender com precisão o uso do processador, você precisa implementar um utilitário que meça o tempo exato de CPU consumido por diferentes operações, o que ajudará a identificar quais cálculos são realmente intensivos em CPU.
Os pacotes necessários de lang.management já foram importados para você.
Este exercicio faz parte do curso
Otimização de Código em Java
Instruções do exercicio
- Recupere a instância de
ThreadMXBeanda classeManagementFactory. - Obtenha o tempo de CPU da thread atual.
exercicio interativo prático
Tente este exercicio completando este código de exemplo.
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");
}
}