这为什么这么快就运行?

问题描述:

我在Windows和Linux上的不同编译器上对阵列,向量,boost :: array进行了基准测试。我遇到了以下奇怪的事情。这为什么这么快就运行?

我对Linux的3.7.0.7 GCC 4.7.2,与国旗:

g++ -O3 -g -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"

而这种代码:

const int arrLength = 5; 
    int a[arrLength]; 
    for (int i = 0; i < arrLength; i++) { 
     a[i] = i * 5; 
    } 

    srand(time(0)); // randomise at run time so it cannot be precomputed by the compiler 
    int numbers[10]; 
    for (auto &i : numbers) 
     i = rand(); 

    clock_t c; 

    c = clock(); 
    for (int i = 0; i < 100000000; i++) { 
     for (int j = 0; j < arrLength; j++) 
      a[j] += numbers[j%10]; 
    } 

    // write it out so the compiler doesn't omit the whole operation if the values in the array are not being used 
    for (int x : a) 
     cout << x; 
    cout << endl; 
    cout << (float) (clock() - c) << endl; 

它实际上是0秒运行一次......怎么能这发生了吗?

我的编译器只是计算最终结果。这里是我的注释的源代码:

asm volatile("DEBUG_IN"); 

for (int i = 0; i < 100000000; i++) 
{ 
    for (int j = 0; j < arrLength; j++) 
    { 
     a[j] += numbers[j % 10]; 
    } 
} 

asm volatile("DEBUG_OUT"); 

的调用是g++ -std=c++11 -O3 -S -masm=intel

结果:

#APP 
# 21 "/tmp/x.cpp" 1 
     DEBUG_IN 
# 0 "" 2 
#NO_APP 
     mov  ecx, DWORD PTR [esp+60] 
     imul edi, DWORD PTR [esp+56], 100000000 
     mov  eax, DWORD PTR [esp+64] 
     mov  edx, DWORD PTR [esp+68] 
     mov  DWORD PTR [esp+36], edi 
     imul edi, ecx, 99999999 
     lea  ecx, [ecx+5+edi] 
     mov  DWORD PTR [esp+40], ecx 
     imul ecx, eax, 99999999 
     lea  eax, [eax+10+ecx] 
     mov  DWORD PTR [esp+44], eax 
     imul eax, edx, 99999999 
     lea  eax, [edx+15+eax] 
     mov  edx, DWORD PTR [esp+72] 
     mov  DWORD PTR [esp+48], eax 
     imul eax, DWORD PTR [esp+72], 99999999 
     lea  eax, [edx+20+eax] 
     mov  DWORD PTR [esp+52], eax 
#APP 
# 31 "/tmp/x.cpp" 1 
     DEBUG_OUT 
# 0 "" 2 
#NO_APP 

正如你所看到的,只是五个简单的任务。请注意,[esp+36][esp+52]指的是numbers的相应元素。

+0

那么编译器只是乘以100000000?我不明白大会.. – 2013-04-21 16:34:36

+0

@Spacemonkey:是的。 – 2013-04-21 17:01:05