Memory alignment on modern processors?

前端 未结 4 996
萌比男神i
萌比男神i 2020-12-08 17:18

I often see code such as the following when, e.g., representing a large bitmap in memory:

size_t width = 1280;
size_t height = 800;
size_t bytesPerPixel = 3;         


        
4条回答
  •  [愿得一人]
    2020-12-08 17:44

    • Does aligning a buffer like this have a performance impact on modern processors?

    Yes. For instance if memcpy is optimized using SIMD instructions (like MMX/SSE) some operations will be faster with aligned memory. In some architectures there are (processor) instructions that fail if the data is not aligned, thus something might work on your machine but not in another one.

    With aligned data you also make a better use of the CPU caches.

    • Should I be worrying about alignment at all, or will the compiler handle this?

    I should worry about alignment when I use dynamic memory and the compiler cannot handle this (see the reply to this comment).

    For other stuff in your code you have the -malign flag and aligned attribute to play with.

提交回复
热议问题