【发布时间】:2021-03-01 11:59:12
【问题描述】:
我写了一个简单的代码来比较 Python 和 C++ 的速度。这是 Python 代码:
def count_permutations(N:int)->int:
count=0
for p in itertools.permutations(range(1,N+1)):
count += 1
return count
这里是 C++ 代码:
int count_permutations(int N) {
vector<int> v(N);
iota(v.begin(), v.end(), 1); // fill the vector with 1,...,N
int count=0;
do {
++count;
} while ( next_permutation(v.begin(),v.end()) );
return count;
}
当我在 Ubuntu 上使用 Python 3.8.5 运行时,我得到:
Permutations of 1..11:
39916800 permutations calculated in 3.31172251701355 seconds
Permutations of 1..12:
479001600 permutations calculated in 40.63520336151123 seconds
当我在同一个 Ubuntu 上使用 C++ (clang++-9) 运行时,没有优化,我得到:
Permutations of 1..11:
39916800 permutations calculated in 5 seconds
Permutations of 1..12:
479001600 permutations calculated in 57 seconds
我觉得这很奇怪,因为在benchmarks 网站上,C++ 总是比 Python 快。
有没有可能最近版本的 Python 变得如此之快以至于它们现在比 C++ 并行更快?
【问题讨论】:
-
你打开编译器优化了吗?这段代码 57 秒看起来太多了,是调试版本吗?
-
@largest_prime_is_463035818 与优化 C++ 确实要快得多。
-
@Caleth 如果不转换为列表就无法工作,对吧?
-
大部分性能来自编译器优化,如果不使用它们,就没有理由期望 C++ 代码性能更好
标签: python c++ performance