为什么在双C的8个字节对齐? [英] Why double in C is 8 bytes aligned?

查看:211
本文介绍了为什么在双C的8个字节对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅​​读有关数据类型的排列在内存中的文章(这里),我无法理解一个点,即

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

请注意,一个双变量将在8字节的边界32被分配
  位机需要两个内存读取周期。在64位机,
  根据银行的数量,双变量将在8字节分配
  边界,并要求只有一个内存读周期。

Note that a double variable will be allocated on 8 byte boundary on 32 bit machine and requires two memory read cycles. On a 64 bit machine, based on number of banks, double variable will be allocated on 8 byte boundary and requires only one memory read cycle.

我的疑问是:为什么double变量需要8字节边界进行分配,而不是4个字节?如果是4字节边界分配还是我们只需要2个内存读周期(在32位计算机上)。纠正我,如果我错了。

My doubt is: Why double variables need to be allocated on 8 byte boundary and not on 4 byte? If it is allocated on 4 byte boundary still we need only 2 memory read cycles(on a 32 bit machine). Correct me if I am wrong.

此外,如果有人对成员/内存对齐一个很好的教程,请分享一下。

Also if some one has a good tutorial on member/memory alignment, kindly share.

推荐答案

对齐尺寸2 ^ N的数据值的2 ^ N的边界上的原因是为了避免该值将在一个高速缓存被分割的可能性行边界。

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.

的X86-32处理器可以获取任何字边界双在最多两个,32位内存读取(8字节对齐与否)。但如果该值跨越高速缓存线边界分割,那么时间来获取第2个字可能是因为需要从存储器中取出一个第二高速缓存线相当长。这会产生不必要的处理器性能不佳。 (作为一个实际问题,当前的处理器不同时取来自存储器32比特;它们倾向于在宽得多的总线取更大的值,以使真正的高数据带宽;实际时间如果抓取两个话他们都在同一高速缓存行,和已经缓存,可能只是1个时钟)。

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.

所以,你应该对性能方面的考虑8字节边界对齐双打。而编译器知道这一点,只是为你做它。

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

这篇关于为什么在双C的8个字节对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆