簡體   English   中英

模板函數+函子參數,為什么函子沒有內聯?

[英]Template function + functor argument, why the functor is not inlined?

下面的代碼執行速度提高了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;
}

編譯器看到一個他無法確定為不改變的函數指針。 我以前見過這幾次。 解決問題的方法是使用一個簡單的包裝器struct

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

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

暫無
暫無

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

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