Yxd:
无聊,测试比较了下仿函数的性能。。。使用仿函数得到的时间节省量还真挺大的。
[阅读: 439] 2004-09-02 10:15:01
#include <iostream>
#include <algorithm>
#include <vector>
#include <time.h>
using namespace std;
template < typename T >
struct MyCompare
{
bool operator()( const T& v1, const T& v2 )
{
return ( v1 > v2 );
}
};
inline bool Compare( int v1, int v2 )
{
return ( v1 < v2 );
}
template < typename FunType >
bool TCompare( int v1, int v2, FunType fun )
{
return fun( v1, v2 );
}
int _tmain(int argc, _TCHAR* argv[])
{
srand( (unsigned)time( NULL ) );
vector< int > theIntArray;
for ( int n = 0; n < 100000; ++ n )
{
theIntArray.push_back( rand() );
}
time_t t1, t2, t3;
time( &t1 );
sort( theIntArray.begin(), theIntArray.end(), Compare );
time( &t2 );
cout << t2 - t1 << _T("seconds has escaped") << endl;
sort( theIntArray.begin(), theIntArray.end(), MyCompare< int >() );
time( &t3 );
cout << t3 - t2 << _T("seconds has escaped") << endl;
return 0;
}