对象数组对齐与 __attribute__aligned() 或 alignas()

Object array alignment with __attribute__aligned() Or alignas()?

本文关键字:alignas aligned attribute 数组 对齐 对象      更新时间:2023-10-16

快速提问伙计们...这些代码刺具有相同的对齐方式吗?

struct sse_t {
     float sse_data[4];
};
// the array "cacheline" will be aligned to 64-byte boundary
struct sse_t alignas(64) cacheline[1000000];

// every object of type sse_t will be aligned to 64-byte boundary
struct sse_t {
     float sse_data[4];
} __attribute((aligned(64)));
struct sse_t cacheline[1000000];

这些代码刺具有相同的对齐方式吗?

差一点。你的两个例子实际上非常不同。

在第一个示例中,您将获得一个sse_t对象的数组。sse_t对象仅保证 4 字节对齐。但由于整个数组都对齐到 64 字节,因此每个 sse_t 对象都将正确对齐以供 SSE 访问。

在第二个示例中,您强制每个sse_t对象对齐到 64 字节。但每个sse_t对象只有 16 个字节。因此,阵列将大 4 倍。(每个sse_t对象的末尾将有 48 个字节的填充)。


struct objA {
     float sse_data[4];
};
struct objB {
     float sse_data[4];
} __attribute((aligned(64)));
int main(){
    cout << sizeof(objA) << endl;
    cout << sizeof(objB) << endl;
}

输出:

16
64

我很确定第二种情况不是你想要的。

但是为什么要对齐到 64 个字节?http://ideone.com/JNEIBR

#include <iostream>
using namespace std;
struct sse_t1 {
     float sse_data[4];
};
// the array "cacheline" will be aligned to 64-byte boundary
struct sse_t1 alignas(64) cacheline1[1000000];
// every object of type sse_t will be aligned to 64-byte boundary
struct sse_t2 {
     float sse_data[4];
} __attribute((aligned(64)));
struct sse_t2 cacheline2[1000000];
int main() {
    cout << "sizeof(sse_t1) = " << sizeof(sse_t1) << endl;
    cout << "sizeof(sse_t2) = " << sizeof(sse_t2) << endl;  
    cout << "array cacheline1 " << (((size_t)(cacheline1) % 64 == 0)?"aligned to 64":"not aligned to 64") << endl;
    cout << "array cacheline2 " << (((size_t)(cacheline2) % 64 == 0)?"aligned to 64":"not aligned to 64") << endl;    
    cout << "cacheline1[0] - cacheline1[1] = " << (size_t)&(cacheline1[1]) - (size_t)&(cacheline1[0]) << endl;
    cout << "cacheline2[0] - cacheline2[1] = " << (size_t)&(cacheline2[1]) - (size_t)&(cacheline2[0]) << endl;  
    return 0;
}

输出:

sizeof(sse_t1) = 16
sizeof(sse_t2) = 64
array cacheline1 aligned to 64
array cacheline2 aligned to 64
cacheline1[0] - cacheline1[1] = 16
cacheline2[0] - cacheline2[1] = 64