Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Copyright 2018, Valentin Debon
- * The following implementation of strlen
- * gives reasonable performances built with
- * clang and -O3, on both Darwin/XNU and GNU/Linux
- * contact me if you have any questions.
- */
- #include <time.h>
- #include <stdio.h>
- #include <stdint.h>
- #include <string.h>
- #define MAGIC_LOW ((unsigned long)-1 / (unsigned char)-1)
- #define MAGIC_HIGH (MAGIC_LOW << 7)
- #define HAS_ZERO_BYTE(x) (((x) - MAGIC_LOW) ^ (x) & MAGIC_HIGH)
- size_t
- strlen(const char *string) {
- const long *aligned;
- const char *iterator = string;
- while(((uintptr_t)iterator % sizeof(long)) != 0) {
- if(*iterator == '\0') {
- return iterator - string;
- }
- iterator++;
- }
- aligned = (const long *)iterator;
- while(HAS_ZERO_BYTE(*aligned) == 0) {
- aligned++;
- }
- iterator = (const char *)aligned;
- while(*iterator != '\0') {
- iterator++;
- }
- return iterator - string;
- }
Add Comment
Please, Sign In to add comment