Disclaimer: this isn't a code review. In fact, this is worse than what the OP wrote. However, it is faster per the OP's request.
###Write a macro
I wrote a macro version of this (see below). The ({...})
is a GCC extension called a statement expression, but if you're not using GCC you can modify the variable ret
and access it afterwards.
Usually macros are faster because they don't need a new stack frame, however I think GCC might still make a stack frame for statement expressions (maybe someone else can weigh in here). Also, the sizeof
will get evaluated at compile time which is one less thing for the program to do at runtime.
Output from my code:
0.0900000000
0.0800000000
0.1000000000
0.0900000000
0.0800000000
0.1000000000
Output from your code
0.1600000000
0.1500000000
0.1500000000
0.1500000000
0.1700000000
0.1900000000
Here is the version of your code I ran:
#include <stdio.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
bool pal(char * text);
int main() {
clock_t start, stop;
start = clock();
for(int j = 0; j < 10000000; j++) {
pal("racecar");
}
stop = clock();
printf("%.10f\n", (double) (stop - start) / CLOCKS_PER_SEC);
return 0;
}
bool pal(char *text) {
char *right = text + strlen(text);
while(text < --right) {
if(*text++ != *right) {
return false;
}
}
return true;
}
And here is what I wrote:
#include <stdio.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
#define pal(STRING) \
({bool ret = true; \
char * left = STRING; \
char * right = left + sizeof(STRING) - 2; \
while(right > left){ \
if(*right != *left){ \
ret = false; \
break; \
} \
--right; \
++left; \
} ret;})
int main() {
clock_t start, stop;
start = clock();
for(int j = 0; j < 10000000; j++) {
pal("racecar");
}
stop = clock();
printf("%.10f\n", (double) (stop - start) / CLOCKS_PER_SEC);
return 0;
}