【发布时间】:2018-02-15 05:00:12
【问题描述】:
大家好,姑娘们。
我的问题很简单,但我没有答案。下面你可以看到我的 C++ 代码 - 它有点大但很简单 - 当我使用 //std::cout<<yy<<endl; (commented) 运行代码时它运行不到 1 秒,当我取消注释该行时它运行大约 2 分钟(我说的是 Release因为在调试中它运行更多时间)。请注意该行只产生很少的输出行(所以问题不在于程序必须调用“cout”太多次)谢谢大家。这是我的代码:
#include <cstdlib>
#include <iostream>
using namespace std;
struct cell {
int x;
int y;
};
int main(int argc, char** argv) {
cell vector[8];
unsigned long int yy=0;
for (int aaa = 0; aaa < 8; aaa++) {
vector[0].x = aaa;
for (int aab = 0; aab < 8; aab++) {
vector[0].y = aab;
for (int aac = 0; aac < 8; aac++) {
vector[1].x = aac;
for (int aad = 0; aad < 8; aad++) {
vector[1].y = aad;
for (int aae = 0; aae < 8; aae++) {
vector[2].x = aae;
for (int aaf = 0; aaf < 8; aaf++) {
vector[2].y = aaf;
for (int aag = 0; aag < 8; aag++) {
vector[3].x = aag;
for (int aah = 0; aah < 8; aah++) {
vector[3].y = aah;
for (int aai = 0; aai < 8; aai++) {
vector[4].x = aai;
for (int aaj = 0; aaj < 8; aaj++) {
vector[4].y = aaj;
for (int aak = 0; aak < 8; aak++) {
vector[5].x = aak;
for (int aal = 0; aal < 8; aal++) {
vector[5].y = aal;
yy++;
if(yy%10000000000==0){
vector[5].y = aal-1;
//std::cout<<yy<<endl;
}
}
}
}
}
}
}
}
}
}
}
}
}
std::cout<<yy<<endl;
std::cout<<vector[5].y<<endl;
return 0;
}
【问题讨论】:
-
天哪,为什么?........
-
天哪,你怎么有耐心写这些嵌套循环???!
-
发生这种情况是因为您的循环除了
cout之外什么都不做,并且可以在没有它的情况下被编译器完全删除。 godbolt.org/g/b8JCSr -
另外,我强烈建议不要生成这种代码,你很可能会攻击 XY 问题。
-
@SergiuVelescu 68719476736 次额外的循环迭代是与众不同的原因。
标签: c++