使用__attribute__aligned()或alignas()对对象数组进行对齐?

4
快速问题,这些代码片段是否具有相同的对齐方式?
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];

简短的回答是不行的。你似乎在这两个片段之间改变了两件事情。你试图解决的更大的问题是什么? - Mysticial
1
抱歉,打错字了...我试图声明一组对齐的sse_t对象数组。 - ARH
2个回答

6
这两个代码片段的对齐方式相同吗?
不完全相同。您的两个示例实际上非常不同。
在第一个示例中,您将获得一个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

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


1

但是为什么你想要将其对齐到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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接