2012-10-03 43 views
1

下面的代碼執行速度提高了4倍,如果在「REPLACING WITH ..」行附近,函數compare_swaps()將被替換爲對my_intcmp()的直接引用。顯然間接使用不是內聯的。爲什麼?模板函數+函子參數,爲什麼函子不內聯?

inline bool my_intcmp(const int & a, const int & b) { 
     return a < b; 
} 


template <class T, class compare> 
void insertion_sort_3(T* first, T* last, compare compare_swaps) { 
    // Count is 1? 
    if(1 == (last - first)) 
     return; 

    for(T* it = first + 1; it != last; it ++) { 
     T val = *it; 
     T* jt; 

     for(jt = it; jt != first; jt --) { 
      // REPLACING WITH if(my_intcmp(val, *(jt - 1)) gives 4x speedup, WHY? 
      if(compare_swaps(val, *(jt - 1))) { 
       *jt = *(jt - 1); 
      } else { 
       break; 
      } 
     } 

     *jt = val; 
    } 
} 

#define SIZE 100000 
#define COUNT 4 

int main() { 
    int myarr[ SIZE ]; 

    srand(time(NULL)); 

    int n = COUNT; 
    while(n--) { 
     for(int i = 0; i < SIZE; i ++) 
      myarr[ i ] = rand() % 20000; 

     insertion_sort_3(myarr, myarr + SIZE, my_intcmp); 
    } 

    return 0; 
} 
+0

哪個編譯器? – Jagannath

+0

順便說一句,如果你想有一個快速的排序算法,你會想要使用比插入排序更有效的算法。 –

+1

「*爲什麼functor沒有內聯?*」 - 因爲'my_intcmp'不是函子。 –

回答

3

編譯器看到一個函數指針,他不能確定它沒有改變。我以前看過幾次。此修復程序的問題是使用一個簡單的包裝struct

struct my_intcmp_wrapper 
{ 
    bool operator()(int v0, int v1) const { 
     return my_intcmp(v0, v1); 
    } 
}; 

專門爲內置的您可能希望通過值而不是通過引用傳遞的對象類型。對於內聯函數,它可能沒有太大區別,但如果函數沒有內聯,它通常會使情況變得更糟。