这是我通常使用的用于在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 和 如何仅使用标准库分配对齐内存?
编辑: 如果有人在意的话,我从Eigen (Eigen/src/Core/util/Memory.h)获取了我的aligned_malloc()函数的想法。
编辑:
我刚刚发现,posix_memalign
在MinGW中未定义。然而,在Visual Studio 2012、GCC、MinGW和Intel C++编译器中,_mm_malloc
都可以使用,因此它似乎是一般情况下最方便的解决方案。它还需要使用自己的_mm_free
函数,不过在某些实现中,您可以将来自_mm_malloc
的指针传递给标准的free
/ delete
。