【发布时间】: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