2013-04-27 247 views
1

我一直在閱讀C++併發的行動書,這裏是使用期貨實現並行快速排序的書中的例子。並行快速排序由單線程快速排序

但我發現這個函數比單線程快速排序函數慢兩倍以上,而不使用C++標準庫中的任何異步工具。 使用g ++ 4.8和visual C++ 2012進行測試。

我用10M隨機整數來測試,並且在visual C++ 2012中,這個函數總共產生了6個線程來執行我的四核PC中的操作。

我對性能非常困惑。任何人都可以告訴我爲什麼?

template<typename T> 
std::list<T> parallel_quick_sort(std::list<T> input) 
{ 
    if(input.empty()) 
    { 
     return input; 
    } 
    std::list<T> result; 
    result.splice(result.begin(),input,input.begin()); 
    T const& pivot=*result.begin(); 
    auto divide_point=std::partition(input.begin(),input.end(), 
     [&](T const& t){return t<pivot;}); 
    std::list<T> lower_part; 
    lower_part.splice(lower_part.end(),input,input.begin(), 
     divide_point); 
    std::future<std::list<T> > new_lower(
     std::async(&parallel_quick_sort<T>,std::move(lower_part))); 
    auto new_higher(
     parallel_quick_sort(std::move(input))); 
    result.splice(result.end(),new_higher); 
    result.splice(result.begin(),new_lower.get()); 
    return result; 
} 
+0

也顯示您的單線程版本 - 您可能花費大量額外時間將數據複製到/從'結果'而不是在排序中的示例代碼... – 2013-04-27 04:32:50

+0

我遵循同一本書,對我而言,它工作得更快。此外,我通過https://www.youtube.com/watch?v=zE9N-KrsMBc&t=126s – Kasun 2017-08-10 13:58:06

回答

1

該代碼只是可怕的次優。例如,爲什麼不是std::list<T> result(input)?爲什麼不是parallel_quick_sort(const std::list<T>& input?簡介它,我敢打賭你會發現各種可怕的事情。在你弄懂代碼的性能之前,你必須確保它花時間去做你認爲它正在做的事情!

+0

得到了更多的見解,我真的懷疑這一點(並提供測試結果)。這基本上是A.Williams(boost線程實現者)的「C++ Concurency in action」中的並行快速排序實現。使用std :: move,並行算法在大數據上運行速度明顯加快。我很懷疑大數據量的快速排序的結果。 – SChepurin 2013-04-28 08:40:51