Pack C/C++ Struct



Pack C/C++ Struct

0 0


struct_pack

slides about c/c++ struct packing

On Github chihungtzeng / struct_pack

Pack C/C++ Struct

Why Struct Packing?

減少記憶體用量 (Esp. 開發嵌入式系統或大型程式) 提高程式運行效率
  • cache line

Careless Struct Packing

int main(int argc, char *argv[]){
    struct {
        char c;         // 1 byte, followed by 7-byte padding
        long long ell;  // 8 bytes
        short s;        // 2 bytes, followed by 6-byte padding
    } s;
    printf("sizeof(s) is %lu\n", sizeof(s));  // sizeof(s) is 24
    return 0;
}

Alignment

  • 1 byte data (char) 可以在任何address
  • 2 byte data (short) 的address是2的倍數
  • 4 byte data (int) 的address是4的倍數
  • pointer 的 address 是4的倍數(32-bit addressing)或8的倍數(64-bit addressing)

Compiler 會在struct中間塞進padding, 以符合alignment

依據使用的記憶體大小, 把data member從大排到小

rearrange

int main(int argc, char *argv[]){
    struct {
        long long ell;  // 8 bytes
        short s;        // 2 bytes
        char c;         // 1 byte, followed by 5-byte padding
    } s;
    printf("sizeof(s) is %lu\n", sizeof(s)); // sizeof(s) is 16
    return 0;
}

24 bytes 變成 16 bytes, 33% improvement!

檢查工具

gcc -Wpadded clang -Wpadded pahole

gcc

int main(int argc, char *argv[]){
    struct {
        char c;         // 1 byte, followed by 7-byte padding
        long long ell;  // 8 bytes
        short s;        // 2 bytes, followed by 6-byte padding
    } s;
    printf("sizeof(s) is %lu\n", sizeof(s));  // sizeof(s) is 24
    return 0;
}

$ gcc -Wpadded bad_struct.c

ad_struct.c: In function ‘main’:
bad_struct.c:6:19: warning: padding struct to align ‘ell’ [-Wpadded]
bad_struct.c:8:5: warning: padding struct size to alignment boundary [-Wpadded]

Clang

$ clang -Wpadded bad_struct.c

bad_struct.c:6:19: warning: padding struct 'struct <anonymous at
      bad_struct.c:4:5>' with 7 bytes to align 'ell' [-Wpadded]
        long long ell;
                  ^
bad_struct.c:4:5: warning: padding size of 'struct <anonymous at
      bad_struct.c:4:5>' with 6 bytes to alignment boundary [-Wpadded]
    struct {
    ^
2 warnings generated.

clang has more detailed output than gcc

pahole (poke-a-hole)

External Links

https://github.com/chihungtzeng/struct_pack.git

0