Created
November 26, 2013 10:35
-
-
Save anonymous/7656323 to your computer and use it in GitHub Desktop.
Possible implementations of strlen.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
// Compile with: clang -O3 -fno-builtin | |
__attribute__((noinline)) int my_strlen(const char *ptr) { | |
int len; | |
asm("xorl %%ecx, %%ecx\n\t" | |
"notl %%ecx\n\t" | |
"xorl %%eax, %%eax\n\t" | |
"cld\n\t" | |
"repne scasb\n\t" | |
"notl %%ecx\n\t" | |
: "=c"(len) | |
: "D"(ptr) | |
: "%eax"); | |
return len; | |
} | |
__attribute__((noinline)) int fast_strlen(const char *ptr) { | |
// Slightly less efficient version of code generated for: | |
// int len = 0; | |
// while(*ptr++) ++len; | |
long len; | |
asm("xorq %0, %0\n\t" | |
"1:\n\t" | |
"cmpb $0, (%1,%0)\n\t" | |
"leaq 1(%0), %0\n\t" | |
"jne 1b\n\t" | |
: "=r"(len) | |
: "r"(ptr)); | |
return len; | |
} | |
const char *str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
int main() { | |
for (long i = 0; i < 100000000; ++i) { | |
my_strlen(str); | |
// Or: fast_strlen, or strlen. | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment