编译时哪个更有效?

时间:2011-07-19 15:08:42

标签: c gcc assembly performance

我知道这些天的计算机速度相当快,而且效率低下,例如我要问的问题,实际上并没有那么重要,但我认为现在仍然很有用。


    int something;
    something = 5;


    int something = 5;

如果编译器以不同方式编译两段代码,则上述两段代码中的哪一段更有效。它可能因编译器而异,但我主要对gcc感兴趣。

6 个答案:

答案 0 :(得分:13)

在这些日子里,当你打开优化时,你(几乎)无法预测生成的代码 ANYTHING 。信不信由你,你的代码描述的是结束不是的手段!所以预测 它将如何执行没有多大意义,特别是在优化之后 - 所有C保证它都会给你你要求的结果。

在优化之前,担心它是没有意义的 并且您的代码琐碎供编译器优化,所以不要担心。

开始考虑程序中更重要的事情。 :)

答案 1 :(得分:5)

即使关闭优化,它也会生成相同的代码。声明变量是为了编译器的利益;它不直接生成代码。

答案 2 :(得分:3)

答案 3 :(得分:0)

它实际上不应该有任何区别 - 编译器会将代码移动得太多,甚至可能无法识别您自己的程序。那说,为什么不自己找出来?

#include <time.h>
#include <stdio.h>

int main ()
{ 
    clock_t start, end;
    double runTime;
    start = clock();

    int i;
    for (i=0; i<10000000; i++}
    {
         int something;
         something = 5;             
    }

    end = clock();
    runTime = (end - start) / (double) CLOCKS_PER_SEC ;
    printf ("Run time one is &#37;g seconds\n", runTime);

    clock_t start, end;
    double runTime;
    start = clock();

    int i;
    for (i=0; i<10000000; i++}
    {
         int something = 5;             
    }

    end = clock();
    runTime = (end - start) / (double) CLOCKS_PER_SEC ;
    printf ("Run time two is &#37;g seconds\n", runTime);
    getchar();
    return 0;
}

答案 4 :(得分:0)

在编译过程中:

 > Both will contribute the same number of tokens and would mean the same.
 > It would have 2 statements to compile and optimize.
 > Since, in compilation it flows through a state machine, so it would even be difficult to notice the difference.

执行过程中:

> Since, both statements mean the same, during optimization stage of compiler both would become equivalent.
> So they will compile to exactly same assembly code.
> In affect, there won't be any difference at all after obj file is generated.

所以,这些事情永远不会有所作为。

答案 5 :(得分:-1)

正如我在编译器优化中所知,如果没有定义,编译器不会保留声明的变量,所以我认为

int something = 5;

比第一个好,因为它在从

中检索变量“something”时减少了编译器的内存和处理工作量
相关问题