Ok, this the std::string vs. strcat() benchmark.
g++-4.1.3 opts: -O3 -march=athlon-xp -Wall -pedantic
Results:
jyrki@pulteri:~$ ./a.out |grep seconds strcat() impl. took 0.149899 seconds. STL impl. took 0.000599 seconds.
The STL string seems to be a shitload of faster than strcat(). The program seems to be working ok, since with 10000 iterations:
jyrki@pulteri:~$ ./a.out |grep bla |wc -l
20000The source:
#include #include #include #include #include #include
#define LOOP_TIMES 10000
static double time_Subtract(struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } return (double)(x->tv_sec - y->tv_sec) + (x->tv_usec - y->tv_usec) / (double)1000000.0; }
int main() { struct timeval t1, t2; const char filler[] = "bla..\n"; gettimeofday(&t1, NULL); size_t bufferLength = LOOP_TIMES * (strlen(filler) + 1); printf("buffer length will be %d bytes.\n", bufferLength); char *buffer = (char *)malloc(bufferLength); if (buffer == NULL) perror("malloc() failed.");
for (int i = 0; i < LOOP_TIMES; i++) { strcat(buffer, filler); } printf("%s\n", buffer); free(buffer); gettimeofday(&t2, NULL); double dt = time_Subtract(&t2, &t1); printf("strcat() impl. took %f seconds.\n", dt); gettimeofday(&t1, NULL); std::string *stlBuffer = new std::string(); stlBuffer->reserve(bufferLength); std::string *stlFiller = new std::string(filler); for (int i = 0; i < LOOP_TIMES; i++) { *stlBuffer += *stlFiller;
} delete stlFiller; gettimeofday(&t2, NULL); printf("%s\n", stlBuffer->c_str()); delete stlBuffer;
dt = time_Subtract(&t2, &t1); printf("STL impl. took %f seconds.\n", dt);
return EXIT_SUCCESS; }