C++:alignas
alignas
alignas 형식 지정자는 변수 및 사용자 정의 형식의 사용자 지정 맞춤을 지정하는 포팅 가능한 C++ 표준 방법입니다.
alignof
마찬가지로 alignof 연산자도 지정된 형식 또는 변수의 맞춤을 얻는 포팅 가능한 표준 방법입니다.
align_malloc
- posix_memalign(3) - Linux man page
- Stackoverflow - OSX lacks memalign
- Stackoverflow - Why use _mm_malloc? (as opposed to _aligned_malloc, alligned_alloc, or posix_memalign)
- MSDN - _aligned_malloc
- posix_memalign(3) - Linux manual page
- Stackoverflow - aligned malloc() in GCC?
- Getting the Most from OpenCL™ 1.2: How to Increase Performance by Minimizing Buffer Copies on Intel® Processor Graphics 1
int *pbuf = (int *)_aligned_malloc(sizeof(int) * 1024, 4096);
// ...
unsigned int verifyZeroCopyPtr(void *ptr, unsigned int sizeOfContentsOfPtr)
{
int status; //so we only have one exit point from function
if((uintptr_t)ptr % 4096 == 0) { // page alignment and cache alignment
if(sizeOfContentsOfPtr % 64 == 0) { // multiple of cache size
status = 1;
} else {
status = 0;
}
} else {
status = 0;
}
return status;
}
Example
struct alignas(16) Bar
{
int i; // 4 bytes
int n; // 4 bytes
alignas(4) char arr[3];
short s; // 2 bytes
};
// ...
cout << alignof(Bar) << endl; // output: 16
Troubleshooting
MacOS X memory alignment
I had a hard time finding a definitive statement on MacOS X memory alignment so I did my own tests. On 10.4/intel, both stack and heap memory is 16 byte aligned. So people porting software can stop looking for memalign() and posix_memalign(). It’s not needed.