编译器是否优化了中介

时间:2014-04-09 23:19:57

标签: c++ optimization compiler-construction

我正在尝试优化以下代码的夸张版本。

int a = startvalue1;
int b = startvalue2;
int c = startvalue3;

int ta = a + b;
int tb = b + c;
int tc = c + a;

int tta = ta * tb;
int ttb = tb * tc;
int ttc = tc * ta;

int finalvalue1 = tta - ttc;
int finalvalue2 = ttb - ttc;
int finalvalue3 = ttc + tta;

编译器会自动摆脱中间人吗?如果没有,如果我摆脱它们,我的代码会运行得更快吗?

我已经分析了我的程序,我必须优化我的离散傅立叶变换。但摆脱中间人将是乏味的,如果编译器要为我做这件事,我想避免它。

1 个答案:

答案 0 :(得分:4)

在使用优化进行编译时,您需要查看编译器的反汇编输出。

如果使用Visual Studio,请设置断点并按ctrl + f11 如果使用gcc,请使用-S标志输出程序集。

在我的系统上,Visual Studio 2012会删除所有中间步骤。

这是我写的测试程序:

#include <iostream>

int main (void)
{
    int startvalue1 = 10 ;
    int startvalue2 = 15 ;
    int startvalue3 = 20 ;

    int a = startvalue1;
    int b = startvalue2;
    int c = startvalue3;

    int ta = a + b;
    int tb = b + c;
    int tc = c + a;

    int tta = ta * tb;
    int ttb = tb * tc;
    int ttc = tc * ta;

    int finalvalue1 = tta - ttc;
    int finalvalue2 = ttb - ttc;
    int finalvalue3 = ttc + tta;

    // This line is only here make sure everything isn't optimized out!
    std::cout << finalvalue1 << finalvalue2 << finalvalue3 ;

    return 0 ;
}

这是优化的装配:

01291270 8B 0D 30 30 29 01    mov         ecx,dword ptr ds:[1293030h]  
01291276 68 59 06 00 00       push        659h  
0129127B 68 2C 01 00 00       push        12Ch  
01291280 6A 7D                push        7Dh  
01291282 FF 15 38 30 29 01    call        dword ptr ds:[1293038h]  
01291288 8B C8                mov         ecx,eax  
0129128A FF 15 38 30 29 01    call        dword ptr ds:[1293038h]  
01291290 8B C8                mov         ecx,eax  
01291292 FF 15 38 30 29 01    call        dword ptr ds:[1293038h]
01291298 33 C0                xor         eax,eax  
0129129A C3                   ret

这大致相当于:

#include <iostream>

int main (void)
{
    std::cout << 125 << 300 << 1625 ;
    return 0 ;
}