Module 21: Debug & Tối ưu

Debug và Tối ưu trong C

assert - Kiểm tra điều kiện

#include <assert.h>
assert(ptr != NULL); // dung chuong trinh neu ptr == NULL

Debug với macro

#ifdef DEBUG
    #define LOG(fmt, ...) printf("[DEBUG] " fmt "\n", ##__VA_ARGS__)
#else
    #define LOG(fmt, ...)
#endif

GDB Commands cơ bản

gcc -g program.c -o program   # bien dich voi -g
gdb ./program
(gdb) break main     # dat breakpoint
(gdb) run            # chay
(gdb) print x        # in bien
(gdb) next           # buoc tiep
(gdb) step           # vao trong ham
(gdb) continue       # tiep tuc
(gdb) quit           # thoat

Tối ưu hóa

// Compiler optimization flags: -O1, -O2, -O3, -Os
inline int max(int a, int b) { return a > b ? a : b; }
register int i; // (goi y) luu trong thanh ghi

restrict

void copy(int *restrict dest, int *restrict src, int n);
// 2 con tro khong tro cung 1 vung nho -> toi uu hon

align - Căn chỉnh bộ nhớ

#include <stdalign.h>
alignas(64) int arr[1000]; // can chinh 64 byte

Tối ưu Cache

  • Truy cập mảng tuần tự (stride 1) nhanh hơn nhảy cóc
  • Dùng struct nhỏ gọn (#pragma pack)
  • Tránh pointer aliasing (dùng restrict)

Profiling

gcc -pg program.c -o program   # bien dich voi -pg
./program                        # chay tao gmon.out
gprof ./program                  # xem profile