为什么这个C++程序比Node.js程序慢



我正在学习C++,并决定重新制作一个旧的Node.js程序,看看它会快多少,因为据我所知,C++应该会因为被编译而快很多。

这个程序很简单,它只是找到素数。它使用与我的Node.js程序完全相同的逻辑,但它需要8到9秒,而Node.js只需要4到5秒。

#include <iostream>
#include <string>
#include <ctime>
using namespace std;

// Declare functions
int main();
bool isPrime(int num);
bool is6n_1(int num);
// Define variables
int currentNum = 5;         // Start at 5 so we iterate over odd numbers, we add 2 and 3 manually
int primesToFind = 1000000;
int primesFound = 2;
int* primes = NULL;

// Main
int main() {
// Create dynamic memory primes array
primes = new int[1000000];
primes[0] = 2;
primes[1] = 3;
cout << "Finding primes..." << endl;
time_t start_time = time(NULL);

// Main execution loop
for (; primesFound < primesToFind; currentNum += 2) {
if (isPrime(currentNum)) {
primes[primesFound] = currentNum;
primesFound++;
}
}
time_t end_time = time(NULL);
cout << "Finished" << endl;
cout << end_time - start_time << endl;
return 0;
}

// Check whether a number is prime
// Dependant on primes[]
bool isPrime(int num) {
// We divide it by every previous prime number smaller than the sqrt
// and check the remainder
for (int i = 1; i <= sqrt(num) && i < primesFound; i++) {       // Start i at 1 to skip the first unnecessary modulo with 2
if (num % primes[i] == 0) {                                 // because we increment by 2
return false;
}
}
return true;
}

因为我是C++的新手,我不知道这是因为代码效率低下(可能(还是因为编译器或Visual Studio IDE中的一些设置。

我使用的是带有O2优化的Visual Studio 2019社区、发布版本和x64体系结构。

如何使此程序更快?

关于编译器设置,我只能说:

  • 使用x64,而不是x86(32位(作为目标
  • 使用Release作为配置,而不是Debug
  • 启用积极的优化

(编辑(编译器中似乎已经有了这些设置,所以对于编译器应该没有什么明显的事情可做。

此外,可能还有很多优化的可能,因为你似乎并没有使用埃拉托斯尼筛。然后,您可以进一步跳过所有2的倍数,并将步长增加到树。

当然,您必须提供node.js代码。我几乎可以肯定,它没有使用完全相同的逻辑。

最新更新