簡體   English   中英

為什么Python比C ++排序更快

[英]Why is Python sort faster than that of C++

在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 VM中使用(僅適用於非基本體)。

這是一個非常了不起的算法,例如,您可以在https://github.com/swenson/sort上找到C ++實現。

保留的教訓:如果后者使用的是性能較差的A&As,那么正確的體系結構算法可以讓您繞開更快的語言 !-)因此,如果您有很大的問題要解決,則可以確定完美的體系結構和解決方案。首先是算法-語言和其中的優化不可避免地是較低優先級的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM