为什么if语句和变量声明要比循环中的添加更快
Why is a if statement and a variable declaration faster than a addition in a loop?
如果我们有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和编译器!哦,我的!"有关如何在这些类型中处理优化器的好建议。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++ 在循环中添加计数器变量并再次初始化其值
- 如何添加循环期间分配的变量?
- 是否可以在 for 循环中添加两个浮点数?
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 添加#pragma循环后出现Segfault
- 在 C++ 中向 rand() 添加模数会影响 for 循环之外的执行,为什么以及如何补救?
- C++ 循环逐行写入文件还是添加到数组并在循环后写入文件?
- 如何从 while 循环中添加数字
- 循环以使用设置模板类将所有 26 个字母添加到 s 中
- C++在 while 循环后添加一行代码会导致错误
- 为什么if语句和变量声明要比循环中的添加更快
- C++:如何在"for"循环中动态地向文本行添加后缀以创建先前声明的变量
- 计算平均值,而不向退出循环添加负等级
- C 如何结束一个段循环,该循环添加数字而不使用数字作为触发器来结束循环
- 我们如何在 C++ 中使用 while 循环添加前 10 个整数
- Qt从其他线程向事件循环添加函数调用
- 如何在C++中阻止循环添加额外的字符迭代
- for循环添加整数