为什么Python的排序比C++的要快

Why is Python sort faster than that of C++

本文关键字:C++ 排序 Python 为什么      更新时间:2023-10-16

在python 3中对int列表进行排序似乎比在C++中对int数组进行排序更快。下面是我用于测试的1个python程序和2个C++程序的代码。C++程序慢的原因是什么?这对我来说没有意义。

-----程序1-python 3.4-----

from time import time
x = 10000
y = 1000
start = time()
for _ in range(y):
    a = list(range(x))
    a.reverse()
    a.sort()
print(round(time() - start, 2), 'seconds')

-----使用排序自算法的程序2-c++------

using namespace std;
#include <iostream>
#include <algorithm>
int main(){
    int x = 10000; 
    int y = 1000;
    int b[10000];
    cout << "start" << endl;
    for (int j = 0; j < y; j++){
        for (int i = 0; i < x; i++){
            b[i] = x - i;
        } // still slower than python with this clause taken out
        sort(b, b + x); // regular sort
    }
    cout << "done";
    system("pause");
}

-----使用手写合并排序的程序3-c++------

using namespace std;
#include <iostream>
void merge(int * arr, int *temp, int first_start, int second_start, int      second_finish){
    int a1 = first_start, b1 = second_start, r = 0;
    while (a1 < second_start && b1 < second_finish){
        if (arr[a1] < arr[b1]){
            temp[r] = arr[a1];
            a1++; r++;
        }
        else {
            temp[r] = arr[b1];
            b1++; r++;
        }
    }
    if (a1 < second_start){
        while (a1 < second_start){
            temp[r] = arr[a1];
            a1++; r++;
        }
    }
    else {
        while (b1 < second_finish){
            temp[r] = arr[b1];
            b1++; r++;
        }
    }
    for (int i = first_start; i < second_finish; i++){
        arr[i] = temp[i - first_start];
    }
}
void merge_sort(int *a, int a_len, int *temp){
    int c = 1, start = 0;
    while (c < a_len){
        while (start + c * 2 < a_len){
            merge(a, temp, start, start + c, start + c * 2);
            start += c * 2;
        }
        if (start + c <= a_len){
            merge(a, temp, start, start + c, a_len);
        }
        c *= 2; start = 0;
    } 
}
int main(){
    int x = 10000; // size of array to be sorted
    int y = 1000; // number of times to sort it
    int b[10000], temp[10000]; 
    cout << "start" << endl;
    for (int j = 0; j < y; j++){
        for (int i = 0; i < x; i++){
            b[i] = x - i; // reverse sorted array (even with this assignment taken out still runs slower than python)
        }
        merge_sort(b, x, temp);
    }
    cout << "done";
    system("pause");
}

核心原因无疑是timsort——http://en.wikipedia.org/wiki/Timsort——最初由Tim Peters为Python设想,但现在也在一些Java虚拟机中(仅用于非基元)。

这是一个非常了不起的算法,您可以在https://github.com/swenson/sort例如

要保留的教训:适当的体系结构算法可以让你绕过据称更快的语言,如果后者使用的是不太完美的A&As!-)因此,如果你有真正大的问题需要解决,首先要确定完美的架构和算法——其中的语言和优化不可避免地是优先级较低的问题。