C++ 对象数组与_属性_aligned()或alignas()对齐?
快速提问,伙计们。。。这些代码尖晶石是否具有相同的对齐方式C++ 对象数组与_属性_aligned()或alignas()对齐?,c++,caching,compiler-optimization,memory-alignment,C++,Caching,Compiler Optimization,Memory Alignment,快速提问,伙计们。。。这些代码尖晶石是否具有相同的对齐方式 struct sse_t { float sse_data[4]; }; // the array "cacheline" will be aligned to 64-byte boundary struct sse_t alignas(64) cacheline[1000000]; 或 这些代码尖晶石是否具有相同的对齐方式 struct sse_t { float sse_data[4]; }; // the
struct sse_t {
float sse_data[4];
};
// the array "cacheline" will be aligned to 64-byte boundary
struct sse_t alignas(64) cacheline[1000000];
或
这些代码尖晶石是否具有相同的对齐方式
struct sse_t {
float sse_data[4];
};
// the array "cacheline" will be aligned to 64-byte boundary
struct sse_t alignas(64) cacheline[1000000];
不完全是。你的两个例子实际上非常不同
在第一个示例中,您将获得一个sse_t
对象数组。sse_t
对象仅保证4字节对齐。但是,由于整个数组对齐到64个字节,因此每个sse\u t
对象都将正确对齐,以便进行sse访问
在第二个示例中,您强制每个sse_t
对象与64字节对齐。但是每个sse_t
对象只有16个字节。因此,阵列将增大4倍。(每个sse_t
对象的末尾将有48个字节的填充)
我很确定第二种情况不是您想要的。但是为什么要对齐到64字节?
简短回答,不。你似乎在片段之间改变了两件事。你想解决的更大的问题是什么?对不起,有个打字错误。。。我正在尝试声明sse_t对象的对齐数组。
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
#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