为什么if语句和变量声明要比循环中的添加更快

Why is a if statement and a variable declaration faster than a addition in a loop?

本文关键字:循环 添加 语句 if 变量 声明 为什么      更新时间:2023-10-16

如果我们有if语句,则具有这样的变量:

#include <iostream>
#include <ctime>
using namespace std;
int main() {
    int res = 0;
    clock_t begin = clock();
    for(int i=0; i<500500000; i++) {
        if(i%2 == 0) {int fooa; fooa = i;}
        if(i%2 == 0) {int foob; foob = i;}
        if(i%2 == 0) {int fooc; fooc = i;}
    }
    clock_t end = clock();
    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
    cout << elapsed_secs << endl;
    return 0;
}

结果是:

1.44
Process returned 0 (0x0)   execution time : 1.463 s
Press any key to continue.

但是,如果是:

#include <iostream>
#include <ctime>
using namespace std;
int main() {
    int res = 0;
    clock_t begin = clock();
    for(int i=0; i<500500000; i++) {
        res++;
        res--;
        res++;
    }
    clock_t end = clock();
    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
    cout << elapsed_secs << endl;
    return 0;
}

结果是:

3.098
Process returned 0 (0x0)   execution time : 3.115 s
Press any key to continue.

为什么添加或减法比具有变量声明的语句需要更多的时间运行?

差异几乎可以肯定是由于编译器优化引起的。您必须查看大会以确保,但这是我对发生的事情的看法:

在第一个示例中,优化器意识到if S的身体没有效果是微不足道的。在每个中,if的可变本地局部都会声明,分配给并立即销毁。因此,if S被优化,留下一个空的for循环,该循环也被优化了。

第二个示例中的站点总体上并不是那么微不足道。 的琐碎的是,环的主体归结为单个res++,很可能会进一步优化++res。但是,由于res不是循环的本地化,因此优化器必须考虑整个main()函数,以意识到循环没有效果。最有可能无法做到。

结论:在当前形式中,测量毫无意义。禁用优化也无济于事,因为您永远不会为生产制造而做到这一点。如果您真的想深入研究这一点,我建议您观看CPPCON 2015:Chandler Carruth" Tuning C :基准,CPU和编译器!哦,我的!"有关如何在这些类型中处理优化器的好建议。