我正在尝试使用英特尔MKL,看起来他们有自己的内存管理(C风格)。
他们建议将他们的MKL_malloc / MKL_free对用于向量和矩阵,我不知道处理它的好方法是什么。其中一个原因是建议内存对齐至少为16字节,并且使用这些例程明确指定它。
我过去依赖auto_ptr和boost :: smart_ptr来忘记内存清理。
如何使用MKL内存管理编写一个异常安全的程序,或者我应该只使用常规的auto_ptr而不是麻烦?
提前致谢。
修改 http://software.intel.com/sites/products/documentation/hpc/mkl/win/index.htm
此链接可以解释我提出问题的原因
更新
我从下面的答案中使用了一个关于分配器的想法。这就是我现在所拥有的:
template <typename T, size_t TALIGN=16, size_t TBLOCK=4>
class aligned_allocator : public std::allocator<T>
{
public:
pointer allocate(size_type n, const void *hint)
{
pointer p = NULL;
size_t count = sizeof(T) * n;
size_t count_left = count % TBLOCK;
if( count_left != 0 ) count += TBLOCK - count_left;
if ( !hint ) p = reinterpret_cast<pointer>(MKL_malloc (count,TALIGN));
else p = reinterpret_cast<pointer>(MKL_realloc((void*)hint,count,TALIGN));
return p;
}
void deallocate(pointer p, size_type n){ MKL_free(p); }
};
如果有人有任何建议,请随时改善。
答案 0 :(得分:2)
使用C ++ new []运算符分配内存,但保留额外的15个字节进行对齐。 然后创建某种包装器,它返回/包含从第一个16字节边界开始的智能指针的内存地址。这会产生16字节对齐的内存。
template
T* address16(T *address) { return (T*)((char*)address + 15) & ~0xf); }
答案 1 :(得分:1)
您可以将std::vector
与自定义分配器(如提及的here)一起使用,以确保16字节对齐。然后,您可以将第一个元素的地址作为MKL函数的输入指针。由于MKL广泛使用SIMD来提高性能,因此您必须具有16字节对齐。