它高度依赖于硬件。
让我演示一下:
#pragma pack( push, 1 )
struct SlowStruct
{
char c;
__int64 a;
int b;
char d;
};
struct FastStruct
{
__int64 a;
int b;
char c;
char d;
char unused[ 2 ]; // fill to 8-byte boundary for array use
};
#pragma pack( pop )
int main (void){
int x = 1000;
int iterations = 10000000;
SlowStruct *slow = new SlowStruct[x];
FastStruct *fast = new FastStruct[x];
// Warm the cache.
memset(slow,0,x * sizeof(SlowStruct));
clock_t time0 = clock();
for (int c = 0; c < iterations; c++){
for (int i = 0; i < x; i++){
slow[i].a += c;
}
}
clock_t time1 = clock();
cout << "slow = " << (double)(time1 - time0) / CLOCKS_PER_SEC << endl;
// Warm the cache.
memset(fast,0,x * sizeof(FastStruct));
time1 = clock();
for (int c = 0; c < iterations; c++){
for (int i = 0; i < x; i++){
fast[i].a += c;
}
}
clock_t time2 = clock();
cout << "fast = " << (double)(time2 - time1) / CLOCKS_PER_SEC << endl;
// Print to avoid Dead Code Elimination
__int64 sum = 0;
for (int c = 0; c < x; c++){
sum += slow[c].a;
sum += fast[c].a;
}
cout << "sum = " << sum << endl;
return 0;
}
酷睿 i7 920 @ 3.5 GHz
slow = 4.578
fast = 4.434
sum = 99999990000000000
好吧,差别不大。但在多次运行中它仍然保持一致。
因此,对齐方式在 Nehalem Core i7 上产生了微小的差异。
英特尔至强 X5482 Harpertown @ 3.2 GHz(Core 2 - 代 Xeon)
slow = 22.803
fast = 3.669
sum = 99999990000000000
现在看一下...
6.2 倍快!!!
结论:
您会看到结果。您可以决定是否值得花时间进行这些优化。
EDIT :
相同的基准,但没有#pragma pack
:
酷睿 i7 920 @ 3.5 GHz
slow = 4.49
fast = 4.442
sum = 99999990000000000
英特尔至强 X5482 Harpertown @ 3.2 GHz
slow = 3.684
fast = 3.717
sum = 99999990000000000
- Core i7 的数字没有变化。显然它可以处理
对于这个基准测试来说,错位没有问题。
- 现在,Core 2 Xeon 的两个版本显示相同的时间。这证实了 Core 2 架构上存在未对齐问题。
摘自我的评论:
如果您省略#pragma pack
,编译器将使所有内容保持一致,这样您就不会看到这个问题。所以这实际上是一个例子,如果你misuse #pragma pack
.