I wrote strlen() for practice but it's really slow. Even if I copy the code from my compiler and run it, it's still slow. This is my test.
/*
strlen_comp
Comparing my and Visual C++'s strlen
by Kimberly Hamrick
*/
#include <assert.h> // for result tests
#include <string.h> // for C++'s strlen()
#include <time.h> // for timing stuff
#include <iostream> // for C++ I/O
using namespace std;
namespace hamrick {
// partial namespace for prototypes
size_t strlen( const char *str );
size_t xstrlen( const char *str );
}
typedef size_t (*strlen_pfunc)( const char * );
void unit_test( const char *title, const char *data, strlen_pfunc func ) {
// add the time for a bunch of runs
clock_t start = clock();
for ( int i = 0; i < 100000000; ++i )
func( data );
cout<< title <<" -- "<< ( double( clock() ) - start ) / CLOCKS_PER_SEC <<endl;
}
int main() {
// test different cases
assert( hamrick::strlen( "" ) == size_t( 0 ) );
assert( hamrick::strlen( "A" ) == size_t( 1 ) );
assert( hamrick::strlen( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) == size_t( 26 ) );
assert( hamrick::strlen( 0 ) == size_t( 0 ) );
// test performance
unit_test( "strlen ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", strlen );
unit_test( "hamrick::strlen ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", hamrick::strlen );
unit_test( "hamrick::xstrlen", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", hamrick::xstrlen );
return 0;
}
namespace hamrick {
// this is my version of strlen
size_t strlen( const char *str ) {
// treat a null pointer as an empty string
size_t len = 0;
if ( str != 0 ) {
// find the end and count each character
while ( *str != '\0' ) {
++len;
++str;
}
}
return len;
}
// I copied this from the compiler source
size_t xstrlen( const char *str ) {
const char *eos = str;
while( *eos++ ) ;
return( eos - str - 1 );
}
}
When I run it hamrick::strlen() and hamrick::xstrlen() are about 10 times slower than strlen()! Why?
strlen -- 1.874
hamrick::strlen -- 9.904
hamrick::xstrlen -- 9.405
Press any key to continue . . .