B
Bartc
I'd been benchmarking my own pet language against Python for manipulation of
short strings. This tested the expression a=b+c for strings, and the Python
code looks like:
b="abc"
c="xyz"
for i in xrange(10000000):
a=b+c
print "A=",a
This took about 2.5 secs with Python 2.5 on my machine (my own efforts
achieved 0.7 secs..)
Pretty good, but how fast could C do it? I expected both of these to be
thrashed, yet the code below took over 4 seconds (mingw 3.4.5 with -O2).
(Timings for longer 60-chars strings were 3.5 secs for Python and 7.5 secs
for C. All timings are elapsed time)
OK, this code is naive and simplistic, but how else would you do it in C?
(BTW I've omitted malloc checking, which is in my own code and I presume is
in Python.)
/* Evaluate string a=b+c 10m times */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void) {
int i,t;
char *a=NULL;
char *b="abc";
char *c="xyz";
t=clock();
for (i=0; i<10000000; ++i) {
free(a);
a=malloc(strlen(b)+strlen(c)+1);
strcpy(a,b);
strcat(a,c);
}
printf("Result=%s\n",a);
printf("Time: %d\n",clock()-t);
}
short strings. This tested the expression a=b+c for strings, and the Python
code looks like:
b="abc"
c="xyz"
for i in xrange(10000000):
a=b+c
print "A=",a
This took about 2.5 secs with Python 2.5 on my machine (my own efforts
achieved 0.7 secs..)
Pretty good, but how fast could C do it? I expected both of these to be
thrashed, yet the code below took over 4 seconds (mingw 3.4.5 with -O2).
(Timings for longer 60-chars strings were 3.5 secs for Python and 7.5 secs
for C. All timings are elapsed time)
OK, this code is naive and simplistic, but how else would you do it in C?
(BTW I've omitted malloc checking, which is in my own code and I presume is
in Python.)
/* Evaluate string a=b+c 10m times */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void) {
int i,t;
char *a=NULL;
char *b="abc";
char *c="xyz";
t=clock();
for (i=0; i<10000000; ++i) {
free(a);
a=malloc(strlen(b)+strlen(c)+1);
strcpy(a,b);
strcat(a,c);
}
printf("Result=%s\n",a);
printf("Time: %d\n",clock()-t);
}