How to determine if memory is aligned?

后端 未结 8 2334
生来不讨喜
生来不讨喜 2020-11-29 18:27

I am new to optimizing code with SSE/SSE2 instructions and until now I have not gotten very far. To my knowledge a common SSE-optimized function would look like this:

<
相关标签:
8条回答
  • 2020-11-29 18:57

    Leave that to the professionals,

    https://www.boost.org/doc/libs/1_65_1/doc/html/align/reference.html#align.reference.functions.is_aligned

    bool is_aligned(const void* ptr, std::size_t alignment) noexcept; 
    

    example:

            char D[1];
            assert( boost::alignment::is_aligned(&D[0], alignof(double)) ); //  might fail, sometimes
    
    0 讨论(0)
  • 2020-11-29 18:59

    With a function template like

    #include <type_traits>
    
    template< typename T >
    bool is_aligned(T* p){
        return !(reinterpret_cast<uintptr_t>(p) % std::alignment_of<T>::value);
    }
    

    you could check alignment at runtime by invoking something like

    struct foo_type{ int bar; }foo;
    assert(is_aligned(&foo)); // passes
    

    To check that bad alignments fail, you could do

    // would almost certainly fail
    assert(is_aligned((foo_type*)(1 + (uintptr_t)(&foo)));
    
    0 讨论(0)
提交回复
热议问题