Я недавно создал программу на Python, которая вычисляет простые числа меньше 1 000 000 и помещает их в список primelist
.Вот оно:
import math
import time
max = 1000000
intlist = []
iflist = []
primelist = [2]
sqrt = round(math.sqrt(max))
counter = 3
start = time.clock()
while (counter < max) :
intlist.append(counter)
iflist.append(0)
counter += 2
counter = 0
counter2 = 0
while intlist[counter] < sqrt:
if (iflist[counter] == 0):
current = intlist[counter]
counter2 = counter + current
while (counter2 < len(iflist)):
iflist[counter2] = 1
counter2 += current
counter += 1
counter = 0
while counter < len(iflist):
if iflist[counter] == 0:
primelist.append(intlist[counter])
counter += 1
print(time.clock() - start)
Эта программа никоим образом не оптимизирована;это просто базовая реализация сита из эратосфена.
Недавно я решил научиться кодировать на C ++.Я написал прямой перевод моего кода Python на C ++, вот он:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <math.h>
#include <time.h>
using namespace std;
int main()
{
auto start = clock();
int max = 1000000;
int squareroot = ceil(sqrt(max));
int current = 0;
vector<int> primelist = { 2 };
vector<int> sieve;
vector<bool> conditions;
vector<int> primes;
for (int n = 3; n < max; n += 2) {
sieve.push_back(n);
conditions.push_back(0);
}
for (int n = 0; sieve[n] < squareroot; n++) {
if (conditions[n] == 0) {
current = sieve[n];
for (int x = n + current; x < conditions.size(); x += current) {
conditions[x] = 1;
}
}
}
for (int n = 0; n < conditions.size(); n++) {
if (conditions[n] == 0) {
primes.push_back(sieve[n]);
}
}
/*for (int n = 0; n < primes.size(); n++) {
cout << primes[n] << endl;
}*/
cout << clock() - start << endl;
}
Из того, что я слышал, C ++ намного быстрее обрабатывает числа, чем Python.Но запуск сценария Python занял 0,74 секунды, а запуск сценария C ++ - 13,29 секунды (согласно выводам обоих)!Почему такая большая разница?Что-то не так с моим кодом?
Я запустил скрипт python с самим python, скомпилировал и запустил скрипт C ++ с Visual Studio 2017. Может ли Visual Studio вызывать эту задержку?Если да, то как мне скомпилировать и запустить программу на C ++ без Visual Studio?У меня проблемы с выяснением этого.
Спасибо за любую помощь!