lundi 22 avril 2013

Provide your own allocator for std::vector or boost storage

If you plan to write some optimized code (SIMD code like SSE or MMX) using memory coming from a standard container (std::vector or boost::numeric::ublas::unbounded_array), your may be interested by the following.


#include <stdlib.h>//linux aligned malloc
#include <malloc.h>
#if defined(WIN32) || defined(WIN64)
#define simd_alloc(alignment, len) _aligned_malloc(len, alignment)
#define simd_free _aligned_free
#else
#define simd_alloc(alignment, len) memalign(alignment, len)
#define simd_free free
#endif

template<typename T>
class aligned_allocator : public std::allocator<T>
{
public:
void deallocate(pointer _Ptr, size_type)
{ // deallocate object at _Ptr, ignore size
simd_free(_Ptr);
}

pointer allocate(size_type _Count)
{ // allocate array of _Count elements
return (T*)simd_alloc(16, _Count*sizeof(T));
}
};



using that allocator class, you can create a vector like:


template struct myType
{
typedef boost::numeric::ublas::vector<T, boost::numeric::ublas::unbounded_array<T, aligned_allocator<T> > > boost_vector;
typedef std::vector<T, aligned_allocator<T> > std_vector;
};

Aucun commentaire :

Enregistrer un commentaire