gpt4 book ai didi

c++ - 未对齐数据的操作速度

转载 作者:可可西里 更新时间:2023-11-01 18:38:45 25 4
gpt4 key购买 nike

据我所知,CPU 在边界上对齐等于该数据大小的数据时性能最佳。例如,如果每个 int 数据的大小都是 4 个字节,那么每个 int 的地址都必须是 4 的倍数才能使 CPU 满意;与 2 字节 short 数据和 8 字节 double 数据相同。出于这个原因,new 运算符和 malloc 函数总是返回一个地址,该地址是 8 的倍数,因此是 4 和 2 的倍数。

在我的程序中,一些旨在处理大字节数组的时间关键算法允许通过将每个连续的 4 个字节转换为 unsigned int 来逐步完成计算,并以这种方式执行算术快多了。但是,字节数组的地址保证是 4 的倍数,因为可能只需要处理字节数组的一部分。

据我所知,英特尔 CPU 可以正确处理未对齐的数据,但会降低速度。如果对未对齐数据的操作速度足够慢,我的程序中的算法将需要重新设计。在这方面,我有两个问题,第一个问题由以下代码支持:

// the address of array0 is a multiple of 4:
unsigned char* array0 = new unsigned char[4];
array0[0] = 0x00;
array0[1] = 0x11;
array0[2] = 0x22;
array0[3] = 0x33;
// the address of array1 is a multiple of 4 too:
unsigned char* array1 = new unsigned char[5];
array1[0] = 0x00;
array1[1] = 0x00;
array1[2] = 0x11;
array1[3] = 0x22;
array1[4] = 0x33;
// OP1: the address of the 1st operand is a multiple of 4,
// which is optimal for an unsigned int:
unsigned int anUInt0 = *((unsigned int*)array0) + 1234;
// OP2: the address of the 1st operand is not a multiple of 4:
unsigned int anUInt1 = *((unsigned int*)(array1 + 1)) + 1234;

所以问题是:

  1. 在 x86、x86-64 和 Itanium 处理器上,OP2 比 OP1 慢多少(如果忽略类型转换和地址增量的成本)?

  2. 编写跨平台可移植代码时,我应该关注哪些类型的处理器未对齐数据访问? (我已经知道 RISC 的了)

最佳答案

市场上有太多的处理器无法给出一个通用的答案。唯一可以肯定的是,有些处理器根本无法进行未对齐访问;如果您的程序打算在同类环境中运行,这对您来说可能重要也可能无关紧要,例如 window 。

在现代高速处理器中,未对齐访问的速度受高速缓存对齐的影响可能比受其地址对齐的影响更大。在当今的 x86 处理器上,缓存行大小为 64 字节。

有一篇维基百科文章可能会提供一些一般指导:http://en.wikipedia.org/wiki/Data_structure_alignment

关于c++ - 未对齐数据的操作速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com