Compiler optimization causing program to run slower

后端 未结 3 1576
孤街浪徒
孤街浪徒 2020-12-11 04:00

I have the following piece of code that I wrote in C. Its fairly simple as it just right bit-shifts x for every loop of for.

int main() {
   int         


        
3条回答
  •  难免孤独
    2020-12-11 04:11

    The optimized loop is producing an infinite loop which is a result of you depending on signed integer overflow. Signed integer overflow is undefined behavior in C and should not be depended on. Not only can it confuse developers it may also be optimized out by the compiler.

    Assembly (no optimizations): gcc -std=c99 -S -O0 main.c

    _main:
    LFB2:
        pushq   %rbp
    LCFI0:
        movq    %rsp, %rbp
    LCFI1:
        movl    $1, -4(%rbp)
        movl    $0, -8(%rbp)
        jmp L2
    L3:
        incl    -8(%rbp)
    L2:
        cmpl    $-2, -8(%rbp)
        jg  L3
        movl    $0, %eax
        leave
        ret
    


    Assembly (optimized level 3): gcc -std=c99 -S -O3 main.c

    _main:
    LFB2:
        pushq   %rbp
    LCFI0:
        movq    %rsp, %rbp
    LCFI1:
    L2:
        jmp L2  #<- infinite loop
    

提交回复
热议问题