【发布时间】:2018-04-25 01:48:33
【问题描述】:
我最近用 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 脚本,并使用 Visual Studio 2017 编译并运行了 C++ 脚本。Visual Studio 会导致这种延迟吗?如果是这样,我如何在没有 Visual Studio 的情况下编译和运行 C++ 程序?我很难弄清楚这一点。
感谢您的帮助!
【问题讨论】:
-
您是在测试调试版本还是发布版本?调试版本专为调试逻辑而设计,速度非常慢。
-
还有一个关于
vector<bool>的警告。 it's a weird sucker 在许多其他地方以牺牲空间效率为目的而设计。 -
...此外,在开始时对每个向量调用
reserve(max)会产生一些改进。 -
... 他说了什么。
std::vector<bool>是个圈套。 -
@user4581301 • 应该有一个经过空间优化的 bool_vector。 :-/
标签: python c++ performance delay primes