我最近在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)
该程序绝不优化;它只是eratosthenes筛子的基本实现。
最近我决定学习如何用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脚本,然后用Visual Studio 2017编译并运行C ++脚本.Visual Studio会导致这种延迟吗?如果是这样,如何在没有Visual Studio的情况下编译和运行C ++程序?我很难搞清楚这一点。
感谢您的帮助!
答案 0 :(得分:2)
https://docs.python.org/3/library/time.html
python中的time.clock是浮点秒
http://www.cplusplus.com/reference/ctime/clock/
c ++中的时钟是点击次数(这取决于每台机器,但每台机器都有&gt; CLOCKS_PER_SEC)
在c ++中我将输出行更正为
auto t = clock() - start;
cout << ((float)t) / CLOCKS_PER_SEC;
&#13;
用于第二级输出
在我的机器上python输出为0.4045815671380151 s,c ++输出为.02s