Code:
#include <iostream>
#include <algorithm>
#include <ctime>
using namespace std;
struct foo
{
foo( int value = 0 )
: value( value )
{ }
int
value;
};
struct cpp_foo_compare
{
cpp_foo_compare( foo const& lhs )
: lhs( lhs )
{ }
inline bool operator ( ) ( foo const& rhs )
{
return lhs.value == rhs.value;
}
foo const&
lhs;
};
int c_foo_compare( void const* lhs, void const* rhs )
{
return ( ( foo const* )lhs )->value == ( ( foo const* )rhs )->value;
}
void* c_find( void const* data, size_t length, size_t span, int ( * compare )( void const*, void const* ), void const* value )
{
unsigned char*
ptr = ( unsigned char* )data;
if( length % span != 0 )
return 0;
while( length-- )
{
if( compare( ptr, value ) )
return ptr;
ptr += span;
}
return 0;
}
void cpp_test( foo const* data, size_t length, foo const* value )
{
find_if( data, data + length, cpp_foo_compare( *value ) );
}
void c_test( foo const* data, size_t length, foo const* value )
{
c_find( data, length, sizeof( foo ), c_foo_compare, value );
}
void hand_coded_test( foo const* data, size_t length, foo const* value )
{
for( foo const* seq = data, * fin = data + length; seq != fin; ++seq )
if( seq->value == value->value )
break;
}
void test
(
char const* name,
foo const* data,
size_t length,
size_t iterations,
void ( * function )( foo const*, size_t, foo const* ),
foo const* value
)
{
clock_t
start,
stop;
start = clock( );
size_t
count = iterations;
while( count-- )
function( data, length, value );
stop = clock( );
cout << "Completed " << iterations << " iterations with function '" << name
<< "' in " << ( double( stop - start ) / CLK_TCK ) << " seconds" << endl;
}
int main( void )
{
size_t const
length = 1024,
iterations = 131072;
foo
data[ length ];
int
target = 3114;
data[ length - 1 ].value = target;
foo
bar( target );
test( "hand_coded_test", data, length, iterations, hand_coded_test, &bar );
test( "c_test", data, length, iterations, c_test, &bar );
test( "cpp_test", data, length, iterations, cpp_test, &bar );
return 0;
}
On my machine the 'cpp_test' was fastest.