繁体   English   中英

为什么这个 C++ 程序比等效的 Node.js 慢?

[英]Why is this C++ program slower than Node.js equivalent?

我正在学习 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 中的某些设置。

我正在使用 Visual Studio 2019 社区、发行版和具有 O2 优化的 x64 架构。

我怎样才能使这个程序更快?

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

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

(编辑)您似乎已经在编译器中进行了这些设置,因此对于编译器应该没有什么明显的事情要做。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM