2013-04-21 1 views
0

필자는 Windows 및 Linux의 다른 컴파일러에서 배열, 벡터, boost :: array를 벤치마킹했습니다. 나는 다음과 같은 이상한 것을 만났다.왜 시간 안에이 실행됩니까?

나는 플래그 리눅스 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초에서 실행 ... 수 이 일이 일어날까요?

답변

3

제 컴파일러는 최종 결과를 계산합니다.

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 

는 불과 5 간단한 과제가있다. [esp+36] ~ [esp+52]numbers의 각 요소를 나타냅니다.

+0

그래서 컴파일러가 숫자에 100000000을 곱하면됩니까? 어셈블리를 이해할 수 없습니다. –

+0

@ Spacemonkey : 예. –

관련 문제