Skip to content

Instantly share code, notes, and snippets.

Created November 26, 2013 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7656323 to your computer and use it in GitHub Desktop.
Save anonymous/7656323 to your computer and use it in GitHub Desktop.
Possible implementations of strlen.
#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