From 4cf3e897054995bf626b7ebf8d6c5079a73c740b Mon Sep 17 00:00:00 2001 From: JCRaymond Date: Sat, 7 Dec 2019 13:49:57 -0500 Subject: [PATCH] Add aligned_allocator --- cpu-opt/aligned_allocator.cpp | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 cpu-opt/aligned_allocator.cpp diff --git a/cpu-opt/aligned_allocator.cpp b/cpu-opt/aligned_allocator.cpp new file mode 100644 index 0000000..84488c6 --- /dev/null +++ b/cpu-opt/aligned_allocator.cpp @@ -0,0 +1,62 @@ +#include +#include + +template +class aligned_allocator +{ + +public: + + typedef T value_type; + typedef T& reference; + typedef const T& const_reference; + typedef T* pointer; + typedef const T* const_pointer; + typedef size_t size_type; + typedef ptrdiff_t difference_type; + + template + struct rebind + { + typedef aligned_allocator other; + }; + + inline aligned_allocator() throw() {} + inline aligned_allocator(const aligned_allocator&) throw() {} + + template + inline aligned_allocator(const aligned_allocator&) throw() {} + + inline ~aligned_allocator() throw() {} + + inline pointer address(reference r) { return &r; } + inline const_pointer address(const_reference r) const { return &r; } + + pointer allocate(size_type n, typename std::allocator::const_pointer hint = 0); + inline void deallocate(pointer p, size_type); + + inline void construct(pointer p, const_reference value) { new (p) value_type(value); } + inline void destroy(pointer p) { p->~value_type(); } + + inline size_type max_size() const throw() { return size_type(-1) / sizeof(T); } + + inline bool operator==(const aligned_allocator&) { return true; } + inline bool operator!=(const aligned_allocator& rhs) { return !operator==(rhs); } +}; + + +template +typename aligned_allocator::pointer +aligned_allocator::allocate(size_type n, typename std::allocator::const_pointer) { + size_type alloc_size = ((sizeof(T)*(n-1))/N + 1)*N; + pointer res = reinterpret_cast(_mm_malloc(alloc_size, N)); + if (res == 0) + throw std::bad_alloc(); + return res; +} + +template +void +aligned_allocator::deallocate(pointer p, size_type) { + _mm_free(p); +}