Why double in C is 8 bytes aligned?

后端 未结 4 1434
时光说笑
时光说笑 2020-12-03 17:08

I was reading a article about data types alignment in memory(here) and I am unable to understand one point i.e.

Note that a double variable will be al

相关标签:
4条回答
  • 2020-12-03 17:46

    8 byte alignment for double on 32 bit architecture doesn't reduce memory reads but it still improve performance of the system in terms of reduced cache access. Please read the following : https://stackoverflow.com/a/21220331/5038027

    0 讨论(0)
  • 2020-12-03 17:50

    Refer this wiki article about double precision floating point format

    The number of memory cycles depends on your hardware architecture which determines how many RAM banks you have. If you have a 32-bit architecture and 4 RAM banks, you need only 2 memory cycle to read.(Each RAM bank contributing 1 byte)

    0 讨论(0)
  • 2020-12-03 17:55

    Aligning a value on a lower boundary than its size makes it prone to be split across two cachelines. Splitting the value in two cachlines means extra work when evicting the cachelines to the backing store (two cachelines will be evicted; instead of one), which is a useless load of memory buses.

    0 讨论(0)
  • 2020-12-03 17:56

    The reason to align a data value of size 2^N on a boundary of 2^N is to avoid the possibility that the value will be split across a cache line boundary.

    The x86-32 processor can fetch a double from any word boundary (8 byte aligned or not) in at most two, 32-bit memory reads. But if the value is split across a cache line boundary, then the time to fetch the 2nd word may be quite long because of the need to fetch a 2nd cache line from memory. This produces poor processor performance unnecessarily. (As a practical matter, the current processors don't fetch 32-bits from the memory at a time; they tend to fetch much bigger values on much wider busses to enable really high data bandwidths; the actual time to fetch both words if they are in the same cache line, and already cached, may be just 1 clock).

    A free consequence of this alignment scheme is that such values also do not cross page boundaries. This avoids the possibility of a page fault in the middle of an data fetch.

    So, you should align doubles on 8 byte boundaries for performance reasons. And the compilers know this and just do it for you.

    0 讨论(0)
提交回复
热议问题