for循环c ++中的微优化

时间:2014-04-22 11:38:16

标签: c++ micro-optimization

让我们假设C++ for循环:

for(int i; i<10;i++)

所以整数需要在开始时分配,然后在每一步都增加并进行比较。所以做这样的事情不会更快:

f or(int i; i++<10;)

因为变量不需要再次加载到存储器中?特别是在制作时volatile

这个小例子代码给出了所有案例的相同结果。 for循环是否仍然得到优化,或者我错过了什么?

#include<iostream>
#include<ctime>

int main() {
    time_t start,ende;
    volatile int dummy = 1;
    const int rep = 1000000000;

    // Method 1
    start = time(0);
    for (int i = 0; i < rep; i++)
            dummy = 1;

    ende = time(0);                         
    std::cout << "Method 1: " << difftime(ende,start)*1000 << " ms" << std::endl;

    // Method 2
    start = time(0);
    for (int i = 0; i++ < rep; )
            dummy = 1;                                                              
    ende = time(0);
    std::cout << "Method 2: " << difftime(ende,start)*1000 << " ms" << std::endl;

    // Method 3
    start = time(0);
    for (volatile int i = 0; i < rep; i++)
            dummy = 1;

    ende = time(0);                         
    std::cout << "Method 3: " << difftime(ende,start)*1000 << " ms" << std::endl;
}

操作系统:Linux 编译器:g ++ 优化:标准(无标志)

2 个答案:

答案 0 :(得分:1)

编译器比你想象的更聪明很多。他们不会产生你认为他们所做的那种虚假负荷。

答案 1 :(得分:1)

优化取决于编译器及其选项。

我建议您反汇编代码,看看优化的结果是什么。 一个简单的好拆解,例如HT editor或IDA第5版(现在免费)。对于一小段代码来说,这很容易。