为什么是数据结构调整的性能非常重要?非常重要、结构调整、性能、数据

2023-09-11 07:31:51 作者:无梦相赠

有人可以给我一个短而合理的解释为什么编译器添加填充到数据结构,以便使会员?我知道它的工作,使CPU可以更有效地访问数据,但我不明白为什么会这样。

如果这仅仅是CPU相关的,为什么双4字节对齐的Linux和8字节对齐的Windows?

解决方案

对齐帮助CPU读取以有效的方式从内存中的数据:更少的高速缓存未命中/冲洗,少总线事务等

某些内存类型(如RDRAM,DRAM等)必须在一个结构化的方式访问,以产生有效的结果(对齐字和爆交易,即很多的话一次)。这是由于许多事情当中,其中:

设置时间:它需要用于存储器装置的时间来访问存储位置 在总线仲裁开销,即许多设备可能需要访问存储设备

填充被用于校正以优化传送效率的数据结构的对准

在换句话说,访问一个不对齐的结构会产生较低的整体性能。这种陷阱的一个很好的例子:假设一个数据结构是不对齐的,需要的CPU /内存控制器,以便获取该结构完成2路公交车交易(而不是1),而性能因此降低。

Can someone give me a short and plausible explanation for why the compiler adds padding to data structures in order to align its members? I know that it's done so that the CPU can access the data more efficiently, but I don't understand why this is so.

数据结构 图总结

And if this is only CPU related, why is a double 4 byte aligned in Linux and 8 byte aligned in Windows?

解决方案

Alignment helps the CPU fetch data from memory in an efficient manner: less cache miss/flush, less bus transactions etc.

Some memory types (e.g. RDRAM, DRAM etc.) need to be accessed in a structured manner (aligned "words" and in "burst transactions" i.e. many words at one time) in order to yield efficient results. This is due to many things amongst which:

setup time: time it takes for the memory devices to access the memory locations bus arbitration overhead i.e. many devices might want access to the memory device

"Padding" is used to correct the alignment of data structures in order to optimize transfer efficiency.

In other words, accessing a "mis-aligned" structure will yield lower overall performance. A good example of such pitfall: suppose a data structure is mis-aligned and requires the CPU/Memory Controller to perform 2 bus transactions (instead of 1) in order to fetch the said structure, the performance is thus consequently lower.