Metriche e misurazioni delle prestazioni

Ottimizzazione del codice in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Oltre le misure di tempo

  • Video precedenti
    • Misurare il tempo delle operazioni
    • Gestione della memoria nella JVM
  • Oltre le misure di tempo
  • Metriche di memoria
  • Metriche di utilizzo CPU
Ottimizzazione del codice in Java

Metriche di memoria con Runtime

// Get the Runtime instance
Runtime runtime = Runtime.getRuntime();


// Memory metrics in bytes long totalMemory = runtime.totalMemory(); // Memory currently allocated long freeMemory = runtime.freeMemory(); // Memory that is unused long maxMemory = runtime.maxMemory(); // Maximum memory JVM will attempt to use
  • Tutti restituiscono numeri long in byte
Ottimizzazione del codice in Java

Capire le metriche di memoria

  • maxMemory(): memoria massima che la JVM proverà a usare (impostata da -Xmx)
  • totalMemory(): memoria attualmente allocata alla JVM
  • freeMemory(): memoria non utilizzata
  • usedMemory(): totalMemory - freeMemory
  • La JVM può aumentare totalMemory fino a maxMemory se serve
Ottimizzazione del codice in Java

Metriche di memoria in pratica

// Create a utility method for readable memory values
public static double getUsedMemoryMB() {
    Runtime runtime = Runtime.getRuntime();
    long memory = runtime.totalMemory() - runtime.freeMemory();
    return memory / (1024.0 * 1024.0);  // Convert to MB
}

// After allocation
System.out.println("Memory used: " + getUsedMemoryMB() + " MB");
Memory used: 5.23 MB
Ottimizzazione del codice in Java

Misurare l'utilizzo della CPU

import java.lang.management.*;

ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

// Check if CPU time measurement is supported if (threadMXBean.isThreadCpuTimeSupported()) { // Enable CPU time measurement threadMXBean.setThreadCpuTimeEnabled(true); // Get CPU time in nanoseconds long cpuTimeNs = threadMXBean.getThreadCpuTime(Thread.currentThread().threadId()); }
Ottimizzazione del codice in Java

Strumenti di profiling Java

  • JVisualVM: interfaccia per monitorare memoria, CPU e altro
  • jmap: strumento da riga di comando per analizzare la memoria
  • Questi tool vanno oltre le semplici metriche viste!
Ottimizzazione del codice in Java

Passons à la pratique !

Ottimizzazione del codice in Java

Preparing Video For Download...