【发布时间】:2013-04-28 22:06:52
【问题描述】:
这是我通常用来与 Visual Studio 和 GCC 对齐内存的代码
inline void* aligned_malloc(size_t size, size_t align) {
void *result;
#ifdef _MSC_VER
result = _aligned_malloc(size, align);
#else
if(posix_memalign(&result, align, size)) result = 0;
#endif
return result;
}
inline void aligned_free(void *ptr) {
#ifdef _MSC_VER
_aligned_free(ptr);
#else
free(ptr);
#endif
}
这段代码一般都好吗?我还看到人们使用_mm_malloc、_mm_free。在大多数情况下,我想要对齐的内存是使用 SSE/AVX。我一般可以使用这些功能吗?这将使我的代码更简单。
最后,创建我自己的函数来对齐内存很容易(见下文)。那么为什么会有这么多不同的常用函数来对齐内存(其中许多只在一个平台上工作)?
此代码进行 16 字节对齐。
float* array = (float*)malloc(SIZE*sizeof(float)+15);
// find the aligned position
// and use this pointer to read or write data into array
float* alignedArray = (float*)(((unsigned long)array + 15) & (~0x0F));
// dellocate memory original "array", NOT alignedArray
free(array);
array = alignedArray = 0;
请参阅:http://www.songho.ca/misc/alignment/dataalign.html 和 How to allocate aligned memory only using the standard library?
编辑: 万一有人关心,我从 Eigen (Eigen/src/Core/util/Memory.h) 中得到了我的对齐 malloc() 函数的想法
编辑:
我刚刚发现 posix_memalign 对于 MinGW 是未定义的。但是,_mm_malloc 适用于 Visual Studio 2012、GCC、MinGW 和 Intel C++ 编译器,因此它似乎是最方便的解决方案。它还需要使用自己的_mm_free 函数,尽管在某些实现中您可以将指针从_mm_malloc 传递到标准free / delete。
【问题讨论】:
-
虽然
unsigned long地址转换可能在实践中有效,但它可能无法在 ILP32 / LP64 / LLP64 (win64) 数据模型之间移植。
标签: c++ c performance sse memory-alignment