【发布时间】:2020-01-12 12:47:29
【问题描述】:
我开始使用 python 中的一个小程序,但运行它需要很长时间,所以我切换到 c++。我之前没有使用这种特定语言的经验(虽然在 c# 中编写了很多代码)并且开始使用网络编辑器:https://www.onlinegdb.com/online_c++_compiler。
我的 C++ 代码是:
clock_t start, end;
/* Recording the starting clock tick.*/
start = clock();
int R = 0;
int x = 0;
for (R = 6; R <= 10000; R = R + 2) {
int X_min = ceil(0.5 * sqrt(2) * R);
int N_pairs = 0;
for (x = X_min; x < R; x++) {
float y = sqrt(pow(R, 2) - pow(x, 2));
if (rint(y) == y) {
N_pairs = N_pairs + 1;
}
}
if (N_pairs >= 4) {
//cout << R << ", " << N_pairs;
//cout << "\n";
}
}
end = clock();
//Calculating total time taken by the program.
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "Time taken by program is : " << time_taken;
cout << " sec " << endl;
//cout << "1" << "|" << "2" << "|" << "3 \n";
//cout << "4" << "|" << "5" << "|" << "6 \n";
//cout << "7" << "|" << "8" << "|" << "9 \n";
一切运行良好,但是 Web 编辑器似乎有一个内置的最大时间边界,所以此时我决定将它交给 Visual Studio。
我复制粘贴代码并运行它:
- 网络编辑器用了 0.272273 秒完成代码
- Visual Studio 用了 2.446 秒来运行它。
我尝试将 VS 从 2017 版更新到 2019 版,但没有效果。
为什么 VS 运行代码需要这么长时间?我该如何解决?
【问题讨论】:
-
您是否启用了发布构建配置?
-
正如@walnut 所说。使用不同的优化/构建标志运行可以发挥巨大的作用。请参阅:godbolt.org/z/jpgVYx,其中一个使用优化级别 3,另一个使用 0。对我来说,这是 30 倍的时间差异。 (虽然编译器与 msvc 不同)
-
我确实启用了发布构建配置。没有它需要更长的时间:8.701 秒
-
您不能在 Windows 上使用
clock来比较性能。 -
使用
sqrt(R*R - x*x)来避免pow(),一定要针对x64。
标签: c++ performance visual-studio-2017 visual-studio-2019