【发布时间】:2019-09-03 05:03:32
【问题描述】:
这个循环:
long n = 0;
unsigned int i, j, innerLoopLength = 4;
for (i = 0; i < 10000000; i++) {
for (j = 0; j < innerLoopLength; j++) {
n += v[j];
}
}
在 0 毫秒内完成,而这个:
long n = 0;
unsigned int i, j, innerLoopLength = argc;
for (i = 0; i < 10000000; i++) {
for (j = 0; j < innerLoopLength; j++) {
n += v[j];
}
}
需要 35 毫秒。 不管 innerLoopLength 是多少,第一种方法总是很快,而第二种方法越来越慢。
有人知道为什么吗?有没有办法加快秒版本的速度?我感谢每一位女士。
完整代码:
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
vector<long> v;
cout << "argc: " << argc << endl;
for (long l = 1; l <= argc; l++) {
v.push_back(l);
}
auto start = chrono::steady_clock::now();
long n = 0;
unsigned int i, j, innerLoopLength = 4;
for (i = 0; i < 10000000; i++) {
for (j = 0; j < innerLoopLength; j++) {
n += v[j];
}
}
auto end = chrono::steady_clock::now();
cout << "duration: " << chrono::duration_cast<chrono::microseconds>(end - start).count() / 1000.0 << " ms" << endl;
cout << "n: " << n << endl;
return 0;
}
使用 -std=c++1z 和 -O3 编译。
【问题讨论】:
-
检查编译后的机器码确定,但编译器可能优化了第一个版本并展开了内部循环,而第二个版本无法以相同的方式优化
-
编译器正在完全优化第一个循环,因此在生成的代码中根本没有循环。
-
为了将来参考,我建议使用godbolt.org 逐步执行您的代码。如果您使用编译器选项复制粘贴您的代码,您会看到生成的程序集有所不同,其中显示了优化发生的位置
-
也许
int main(const int argc, char*argv[])有帮助。 IE。告诉编译器argc不会改变。 -
在godbolt上试过
const int argc,和int argc没有区别
标签: c++ linux performance for-loop g++