I have the following simple code and when I compiling them in GCC and Clang there is a huge performance difference between theirs execute times as you can see the results and the versions of the compilers below.
char* strchr_x(register const char* s, int c) {
do {
if (*s == c) {
return (char*)s;
}
} while (*s++);
return 0;
}
char* get(char* value, const char seperator) {
int seperator_index = strchr(value, seperator) - value;
char* result = malloc(seperator_index);
memcpy(result, value, seperator_index);
result[seperator_index] = '\0';
return result;
}
int main() {
const char seperator = ',';
clock_t t = clock();
for (size_t i = 0; i < 100000000; ++i) {
free(get("127.0.0.1, 127.0.0.2:1111", seperator));
}
float elapsed_seconds = (((double)(clock() - t)) / CLOCKS_PER_SEC);
printf("%f seconds.\n", elapsed_seconds);
return 0;
}
gcc version 8.1.0 (Ubuntu 8.1.0-5ubuntu1~16.04)
# gcc main.c -O3 -o gcc-main
# 1.968750 seconds.
clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)
# clang main.c -O3 -o clang-main
# 0.000000 seconds.
Additionally, the 'strchr_x' implementation is exactly the same with original GCC implementation. You can see it at https://github.com/gcc-mirror/gcc/blob/master/libiberty/strchr.c
When I use the 'strchr' method in the standard library; GCC's run time reducing to 0.015625 seconds.
So, my questions are:
- Why there is huge performace difference between my 'strchr_x' and the standard library's 'strchr' in GCC?
- Why there is this huge performace gap between in GCC and Clang?