【发布时间】:2017-07-25 01:19:48
【问题描述】:
如果我们有这样声明变量的 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 语句要长?
【问题讨论】:
-
因为带有变量声明的 if 语句实际上什么都不做,因此它不存在。 E:虽然现在我看了一下,这些循环都没有做任何事情,所以为了得到任何经过的时间,你必须在编译时抑制优化。这使得结果毫无意义,但这也意味着我最初的猜测不适用。
-
检查您的汇编代码以查看优化效果。
-
当编译器因禁用优化而瘫痪时,查看生成的代码的运行时是没有用的。使用
-O2或/O2重试。 -
你的测试完全没有意义。编译器有权根据“as-if”规则完全消除第一个循环,无论是否指定优化。