VS 2017 和 2019 运行 c++ 真的很慢

VS 2017 & 2019 run c++ really slow

本文关键字:真的 c++ 运行 2017 2019 VS      更新时间:2023-10-16

我从python的小程序开始,但运行它需要很长时间,所以我切换到c ++。我没有这种特定语言的早期经验(尽管用 c# 编码了很多(,并且从 Web 编辑器开始: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。

我复制粘贴的代码并运行它:

  • Web 编辑器花了 0.272273 秒来完成代码
  • Visual Studio花了2.446秒来运行它。

我尝试将VS从2017版本更新到2019版本,但没有效果。

为什么VS运行代码需要这么长时间??我该如何解决它?

主要问题是 VC++ 不内联rint(float)调用:

movaps  xmm0, xmm6
call    rint
ucomisd xmm0, xmm6

链接到 Godbolt

您可以通过将rint(y)替换为"手动"舍入来期待良好的加速:

改变

if (rint(y) == y) {

if (int(y+0.5) == y) {

在我的机器上从0.8 秒下降到0.04 秒(用/O2 /fp:fast编译(

此外,您需要在循环外使用N_pairs否则(好的(编译器可以优化所有内容。

优化的第一条规则:不正确程序的性能无关紧要。

看来您正在寻找x^2 + y^2 = R^2的整数解。但是,将float数据类型用于中间存储会产生大量误报。将N_pairs移出循环(以防止完全删除该循环,如@rustyx所述,并计算所有对(结果为 7886 对;double:5681。

最后一个数字也对应于完全整数检查,这要快得多(在我的系统上为 21 毫秒(。这是我的代码:

#include <iostream>
#include <chrono>
int main()
{
auto t = std::chrono::high_resolution_clock::now();
int N_pairs = 0;
double d = 0.5 * sqrt(2);
for (int R = 6; R <= 10000; R = R + 2) {
int X_min = ceil(d * R);
for (int x = X_min; x < R; x++) {
int y = sqrtf(R * R - x * x);
if(x*x + y*y == R*R) {
N_pairs = N_pairs + 1;
}
}
}
std::cout << "Time taken by program is: " 
<< std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t).count() 
<< " ms" << std::endl;
std::cout << "N_pairs: " << N_pairs << std::endl; // with float: 7886; with double or int: 5681
return 0;
}