CPU和数据对齐 [英] CPU and Data alignment

查看:27
本文介绍了CPU和数据对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你觉得这个问题已经回答了很多次,请原谅我,但我需要回答以下问题!

Pardon me if you feel this has been answered numerous times, but I need answers to the following queries!

  1. 为什么数据必须对齐(在 2 字节/4 字节/8 字节边界上)?我的疑问是,当 CPU 具有地址线 Ax Ax-1 Ax-2 ... A2 A1 A0 时,很有可能按顺序对内存位置进行寻址.那么为什么需要在特定边界对齐数据?

  1. Why data has to be aligned (on 2-byte / 4-byte / 8-byte boundaries)? Here my doubt is when the CPU has address lines Ax Ax-1 Ax-2 ... A2 A1 A0 then it is quite possible to address the memory locations sequentially. So why there is the need to align the data at specific boundaries?

如何在编译代码和生成可执行文件时找到对齐要求?

How to find the alignment requirements when I am compiling my code and generating the executable?

如果例如数据对齐是 4 字节边界,这是否意味着每个连续字节都位于模 4 偏移量处?我的疑问是数据是否是 4 字节对齐的,这是否意味着如果一个字节在 1004,那么下一个字节在 1008(或在 1005)?

If for e.g the data alignment is 4-byte boundary, does that mean each consecutive byte is located at modulo 4 offsets? My doubt is if data is 4-byte aligned does that mean that if a byte is at 1004 then the next byte is at 1008 (or at 1005)?

推荐答案

CPU 是面向字的,而不是面向字节的.在简单的 CPU 中,内存通常配置为每个地址选通返回一个 (32 位、64 位等),其中底部的两个(或更多)地址线通常是无关位.

CPUs are word oriented, not byte oriented. In a simple CPU, memory is generally configured to return one word (32bits, 64bits, etc) per address strobe, where the bottom two (or more) address lines are generally don't-care bits.

Intel CPU 可以对许多指令执行非字边界的访问,但是存在性能损失,因为 CPU 在内部执行两次内存访问和一个数学运算来加载一个字.如果您正在执行字节读取,则不适用对齐.

Intel CPUs can perform accesses on non-word boundries for many instructions, however there is a performance penalty as internally the CPU performs two memory accesses and a math operation to load one word. If you are doing byte reads, no alignment applies.

某些 CPU(ARM 或 Intel SSE 指令)需要对齐的内存,并且在进行未对齐的访问(或引发异常)时有未定义的操作.它们不实施更复杂的加载/存储子系统,从而节省了大量的芯片空间.

Some CPUs (ARM, or Intel SSE instructions) require aligned memory and have undefined operation when doing unaligned accesses (or throw an exception). They save significant silicon space by not implementing the much more complicated load/store subsystem.

对齐方式取决于 CPU 字大小(16、32、64 位),或者在 SSE 的情况下取决于 SSE 寄存器大小(128 位).

Alignment depends on the CPU word size (16, 32, 64bit) or in the case of SSE the SSE register size (128 bits).

对于您的最后一个问题,如果您一次加载一个数据字节,则大多数 CPU 没有对齐限制(某些 DSP 没有字节级指令,但您可能不会遇到).

For your last question, if you are loading a single data byte at a time there is no alignment restriction on most CPUs (some DSPs don't have byte level instructions, but its likely you won't run into one).

这篇关于CPU和数据对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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