大佬教程收集整理的这篇文章主要介绍了为什么这个 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 架构。
我怎样才能使这个程序更快?
关于编译器设置,我只能说:
(编辑)您似乎已经在编译器中设置了这些设置,因此对于编译器应该没有什么明显的事情要做。
此外,可能有很多优化可能,因为您似乎没有使用 Eratosthenes 筛。然后,您可以进一步跳过所有 2 的倍数,并将步长增加为树。
您当然必须提供 node.js 代码。我几乎可以肯定它没有使用完全相同的逻辑。
以上是大佬教程为你收集整理的为什么这个 C++ 程序比 Node.js 等价程序慢?全部内容,希望文章能够帮你解决为什么这个 C++ 程序比 Node.js 等价程序慢?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。