[英]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.