2017-09-26 88 views
1

自定義lambda比較器比正常函數C++慢11。我經歷了幾次。但是,仍然無法弄清楚這是爲什麼。有沒有人體驗過這一點,並瞭解其背後的原因?C++ 11 Lambda自定義比較器減慢排序

#include <bits/stdc++.h> 
    using namespace std; 

    const int N = 1e4 + 1; 
    vector<int> v(N); 
    vector<int> sorted(N); 
    map<int, int> counts; 
    long long start; 

    void startClock() { 
     start = clock(); 
    } 

    void stopClock() { 
     cout << float(clock() - start)/CLOCKS_PER_SEC << endl; 
    } 

    void copyOriginal() { 
     for (int i = 0; i < N; ++i) 
      sorted[i] = v[i]; 
    } 

    void sortWLambda(map<int, int>& counts) { 
     cout << "sorting with lambda" << endl; 
     sort(sorted.begin(), sorted.end(), [counts](const int& a, const int& b) { 
      if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b); 
      return a < b; 
     }); 
    } 

    bool comparator(const int& a, const int& b) { 
     if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b); 
     return a < b; 
    } 

    void sortWoLambda() { 
     cout << "sorting w/o lambda" << endl; 
     sort(sorted.begin(), sorted.end(), comparator); 
    } 

    int main() { 
     for (int i = 0; i < N; ++i) { 
      int num = rand() % 1234; 
      counts[num]++; 
      v[i] = num; 
     } 

     copyOriginal(); 
     startClock(); 
     sortWLambda(counts); 
     stopClock(); 

     copyOriginal(); 
     startClock(); 
     sortWoLambda(); 
     stopClock(); 

     return 0; 
    } 

與拉姆達6.28秒

通過引用排序的w/o拉姆達0.17秒

+0

您是否正在測試優化版本?兩者都得到0.017。 –

+1

'counts'正被複制到lambda中,我不認爲它會影響那麼多,但它看起來像是這樣:https://ideone.com/9nS4aw – vu1p3n0x

+0

是的,我發現相同。 http://coliru.stacked-crooked.com/a/55686912d7561578 Visual Studio是同一時間複製與否。切換到無序的地圖甚至更好。 –

回答

0

通排序作出對拉姆達的差異。

我想這個..

 sort(sorted.begin(), sorted.end(), [&counts](const int& a, const int& b) { 
      if (*counts.find(a) != *counts.find(b)) return *counts.find(a) < *counts.find(b); 
      return a < b; 
     }); 

現在這需要同時作爲普通功能

Passing by constant reference in the lambda capture list幫我呢!