Advertisement
Guest User

Untitled

a guest
Mar 19th, 2016
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <string.h>
  2. #include <limits.h>
  3.  
  4. #define LBLOCKSIZE   (sizeof (long))
  5. #define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
  6.  
  7. #if LONG_MAX == 2147483647L
  8. #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
  9. #else
  10. #if LONG_MAX == 9223372036854775807L
  11. /* Nonzero if X (a long int) contains a NULL byte. */
  12. #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
  13. #else
  14. #error long int is not a 32bit or 64bit type.
  15. #endif
  16. #endif
  17.  
  18. #ifndef DETECTNULL
  19. #error long int is not a 32bit or 64bit byte
  20. #endif
  21.  
  22. __attribute_noinline__ size_t strlen_newlib(const char *str)
  23. {
  24.   const char *start = str;
  25.  
  26. #if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
  27.   unsigned long *aligned_addr;
  28.  
  29.   /* Align the pointer, so we can search a word at a time.  */
  30.   while (UNALIGNED (str))
  31.     {
  32.       if (!*str)
  33.     return str - start;
  34.       str++;
  35.     }
  36.  
  37.   /* If the string is word-aligned, we can check for the presence of
  38.      a null in each word-sized block.  */
  39.   aligned_addr = (unsigned long *)str;
  40.   while (!DETECTNULL (*aligned_addr))
  41.     aligned_addr++;
  42.  
  43.   /* Once a null is detected, we check each byte in that block for a
  44.      precise position of the null.  */
  45.   str = (char *) aligned_addr;
  46.  
  47. #endif /* not PREFER_SIZE_OVER_SPEED */
  48.  
  49.   while (*str)
  50.     str++;
  51.   return str - start;
  52. }
  53.  
  54.  
  55. #if defined newlib
  56. #define strlen strlen_newlib
  57. #endif
  58.  
  59. __attribute_noinline__ uint64_t bench_strlen(char * in, uint64_t n) {
  60.   uint64_t s = 0;
  61.   do {
  62.     s += (strlen(in) * rand());
  63.   } while(--n);
  64.   return s;
  65. }
  66.  
  67.  
  68. int main(void) {
  69.   uint64_t len = 1024 * 10;
  70.   void * str = malloc(len);
  71.   memset(str, 1, len - 1);
  72.  
  73.   fprintf(stderr, "%lu\n", bench_strlen(str, 10050000));
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement