【问题标题】:Template function + functor argument, why the functor is not inlined?模板函数+函子参数,为什么函子没有内联?
【发布时间】:2012-10-03 23:39:01
【问题描述】:

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

【问题讨论】:

  • 顺便说一句,如果你想要一个快速的排序算法,你会想要使用比插入排序更有效的算法。
  • "为什么函子没有内联?" -- 因为my_intcmp 不是函子。
  • GCC 4.2,-O3 选项。使用带有内联 operator() 的真正函子会有所帮助。
  • @DietmarKühl:插入排序非常适合大多数排序的集合,例如在将一个元素插入/更新到/在已经排序的容器中之后。

标签: c++ templates inline compiler-optimization functor


【解决方案1】:

编译器看到一个函数指针,他无法确定它没有改变。我以前见过几次。解决问题的方法是使用简单的包装器struct:

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

特别是对于内置类型,您可能希望通过值而不是通过引用传递对象。对于内联函数,它可能没有太大的区别,但如果函数没有内联,它通常会使情况变得更糟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多