编译器优化方案导致运行速度慢 [英] Compiler optimization causing program to run slower

查看:523
本文介绍了编译器优化方案导致运行速度慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面这段code的,我在C.其写下相当简单,因为它正好位移位 X 为每一个循环。

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 x = 1;
   for (int i = 0; i > -2; i++) {
      x >> 2;
   }
}

现在正在发生奇怪的是,当我刚刚编译它没有任何的优化或第一级优化( -O ),它运行得很好(我定时可执行文件及其有关 1.4S -O 5.4S 无任何优化。

Now the strange thing that is happening is that when I just compile it without any optimizations or with first level optimization (-O), it runs just fine (I am timing the executable and its about 1.4s with -O and 5.4s without any optimizations.

现在,当我加入 -O2 -O3 开关编译和时间生成的可执行文件,这不是' ŧ停止(我已经测试高达 60 )。

Now when I add -O2 or -O3 switch for compilation and time the resulting executable, it doesn't stop (I have tested for up to 60s).

这是什么可能导致此任何想法?

Any ideas on what might be causing this?

推荐答案

优化循环产生无限循环是根据签署整数溢出你的结果。有符号整数溢出是ç未定义行为,不应该依赖。不仅可以将它混淆开发它也可以由编译器优化出

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.

大会(不优化):的gcc -std = C99 -S -O0的main.c

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



大会(优化的3级):GCC -std = C99 -S -O3的main.c

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

这篇关于编译器优化方案导致运行速度慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆