Chỉ số hiệu năng và đo lường

Tối ưu hóa mã trong Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Vượt ra ngoài đo thời gian

  • Video trước
    • Đo thời gian thực thi thao tác
    • Quản lý bộ nhớ trong JVM
  • Vượt ra ngoài đo thời gian
  • Chỉ số bộ nhớ
  • Chỉ số sử dụng CPU
Tối ưu hóa mã trong Java

Chỉ số bộ nhớ với 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
  • Tất cả trả về số long biểu thị byte
Tối ưu hóa mã trong Java

Hiểu các chỉ số bộ nhớ

  • maxMemory(): Mức bộ nhớ tối đa JVM sẽ dùng (thiết lập bằng -Xmx)
  • totalMemory(): Bộ nhớ hiện cấp phát cho JVM
  • freeMemory(): Bộ nhớ chưa dùng
  • usedMemory(): totalMemory - freeMemory
  • JVM có thể tăng totalMemory đến maxMemory khi cần
Tối ưu hóa mã trong Java

Chỉ số bộ nhớ trong thực tiễn

// 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
Tối ưu hóa mã trong Java

Đo mức sử dụng 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()); }
Tối ưu hóa mã trong Java

Công cụ profiling Java

  • JVisualVM: Giao diện giám sát bộ nhớ, CPU và hơn thế
  • jmap: Công cụ dòng lệnh phân tích bộ nhớ
  • Các công cụ này vượt xa các chỉ số cơ bản đã nêu!
Tối ưu hóa mã trong Java

Luyện tập nào!

Tối ưu hóa mã trong Java

Preparing Video For Download...