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