开发者

How to see the code generated by the compiler

开发者 https://www.devze.com 2022-12-25 05:07 出处:网络
Guys in one of excersises (ch.5,e.8) from TC++PL Bjarne asks to do following: \'\"Run some tests to see if your compiler really generates equivalent code for iteration using pointers and iteration usi

Guys in one of excersises (ch.5,e.8) from TC++PL Bjarne asks to do following:

'"Run some tests to see if your compiler really generates equivalent code for iteration using pointers and iteration using indexing. If different degrees of optimization can be requested, see if and how that affects the quality of the gene开发者_如何学Gorated code"'

Any idea how to eat it and with what? Thanks in advice.


You want to write code something like this:

int a[] = {1,2,3,4};
int n = 0;
for ( int i = 0; i < 4; i++ ) {
   n += a[i];
}

int * p = a;
for ( int i = 0; i < 4; i++ ) {
   n += *p++;
}

Then you need to compile it with compiler options that gets your compiler to emit assembly language, and take a look at it. It's also instructive to do this both with and without optimisations turned on.


int sum_with_array_indexing(int* p, int size)
{
    int s = 0;
    for (int i = 0; i < size; ++i)
    {
        s += p[i];
    }
    return s;
}

int sum_with_pointer_arithmetic(int* p, int size)
{
    int s = 0;
    for (int i = 0; i < size; ++i)
    {
        s += *p++;
    }
    return s;
}

g++ -S -O2 yields identical code:

__Z23sum_with_array_indexingPii:
LFB0:
    pushl   %ebp
LCFI0:
    movl    %esp, %ebp
LCFI1:
    pushl   %ebx
LCFI2:
    movl    8(%ebp), %ebx
    movl    12(%ebp), %ecx
    testl   %ecx, %ecx
    jle L8
    xorl    %edx, %edx
    xorl    %eax, %eax
    .p2align 2,,3
L4:
    addl    (%ebx,%edx,4), %eax
    incl    %edx
    cmpl    %ecx, %edx
    jne L4
L3:
    popl    %ebx
    leave
    ret
L8:
    xorl    %eax, %eax
    jmp L3

and:

__Z27sum_with_pointer_arithmeticPii:
LFB1:
    pushl   %ebp
LCFI3:
    movl    %esp, %ebp
LCFI4:
    pushl   %ebx
LCFI5:
    movl    8(%ebp), %ebx
    movl    12(%ebp), %ecx
    testl   %ecx, %ecx
    jle L15
    xorl    %eax, %eax
    xorl    %edx, %edx
    .p2align 2,,3
L12:
    addl    (%ebx,%edx,4), %eax
    incl    %edx
    cmpl    %ecx, %edx
    jne L12
L11:
    popl    %ebx
    leave
    ret
L15:
    xorl    %eax, %eax
    jmp L11
0

精彩评论

暂无评论...
验证码 换一张
取 消