“内存是 8 字节对齐的"是什么意思? [英] What is meant by "memory is 8 bytes aligned"?

查看:207
本文介绍了“内存是 8 字节对齐的"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行一个项目时,我看到内存数据是8 个字节对齐的".谁能解释一下这是什么意思?

While going through one project, I have seen that the memory data is "8 bytes aligned". Can anyone please explain what this means?

推荐答案

8 字节对齐"的对象存储在 8 的倍数的内存地址处.

An object that is "8 bytes aligned" is stored at a memory address that is a multiple of 8.

许多 CPU 只会从对齐的位置加载某些数据类型;在其他 CPU 上,这种访问速度更快.使用内存对齐还有其他几个可能的原因 - 没有看到代码就很难说为什么.

Many CPUs will only load some data types from aligned locations; on other CPUs such access is just faster. There's also several other possible reasons for using memory alignment - without seeing the code it's hard to say why.

对齐访问速度更快,因为到内存的外部总线不是单字节宽——它通常是 4 或 8 字节宽(甚至更宽).这意味着 CPU 一次不会获取一个字节 - 它从请求的地址开始获取 4 或 8 个字节.因此,内存地址的 2 或 3 个最低有效位实际上不是由 CPU 发送的 - 外部存储器只能在总线宽度倍数的地址处读取或写入.如果您在地址9"处请求一个字节,CPU 实际上会向内存请求从地址 8 开始的字节块,并将第二个字节加载到您的寄存器中(丢弃其他字节).

Aligned access is faster because the external bus to memory is not a single byte wide - it is typically 4 or 8 bytes wide (or even wider). This means that the CPU doesn't fetch a single byte at a time - it fetches 4 or 8 bytes starting at the requested address. As a consequence of this, the 2 or 3 least significant bits of the memory address are not actually sent by the CPU - the external memory can only be read or written at addresses that are a multiple of the bus width. If you requested a byte at address "9", the CPU would actually ask the memory for the block of bytes beginning at address 8, and load the second one into your register (discarding the others).

这意味着未对齐的访问可能需要从内存中读取两次:如果您要求从地址 9 开始的 8 个字节,则 CPU 必须获取从地址 8 开始的 8 个字节以及 8从地址 16 开始的字节,然后屏蔽掉你想要的字节.另一方面,如果您要求从地址 8 开始的 8 个字节,则只需要一次提取.有些 CPU 甚至不会执行这种未对齐的加载 - 它们只会引发异常(甚至默默加载错误的数据!).

This implies that a misaligned access can require two reads from memory: If you ask for 8 bytes beginning at address 9, the CPU must fetch the 8 bytes beginning at address 8 as well as the 8 bytes beginning at address 16, then mask out the bytes you wanted. On the other hand, if you ask for the 8 bytes beginning at address 8, then only a single fetch is needed. Some CPUs will not even perform such a misaligned load - they will simply raise an exception (or even silently load the wrong data!).

这篇关于“内存是 8 字节对齐的"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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