/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdlib.h>

static const unsigned long magic = 0x01010101;

size_t strlen1(const char *s)
{
  const char *t = s;
  unsigned long word;

  if (!s) return 0;

  /* Byte compare up until word boundary */
  for (; ((unsigned long) t & 3); t++)
    if (!*t) return t - s;

  /* Word compare */
  do {
    word = *((unsigned long *) t); t += 4;
    word = (word - magic) &~ word;
    word &= (magic << 7);
  } while (word == 0);

#if BYTE_ORDER == LITTLE_ENDIAN
  /* word & 0x80808080 == word */
  word = (word - 1) & (magic << 10);
  word += (word << 8) + (word << 16);
  t += word >> 26;
#else
  if ((word & 0x80800000) == 0) {
    word <<= 16;
    t += 2;
  }
  if ((word & 0x80000000) == 0) t += 1;
#endif
  return ((const char *) t) - 4 - s;
}

size_t strlen2(const char *s)
{
   int ix = 0;
   while(s[ix]) ix++;
   return ix;
}

size_t strlen3(const char *s)
{
   char *p = (char *)s;
   while(*p) p++;
   return (p-s);
}

size_t strlen4(const char *s)
{
   char *p = (char *)s;
   long l;
   while(((int)p)%4!=0)
   {
      if(!*p) return (p-s);
      p++;
   }
   for(;;) {
      l = *(long *)p;
      if(!(l & 0x000000FF)) return (p-s);
      if(!(l & 0x0000FF00)) return (p-s+1);
      if(!(l & 0x00FF0000)) return (p-s+2);
      if(!(l & 0xFF000000)) return (p-s+3);
      p+=4;
   }
}

#include <stdio.h>
#include <string.h>
#include <time.h>

#define N 100000000
#define S "abcdefgijhklmopqrstuvwxyz0123456789"

int main()
{
   int i;
   time_t t1,t2;
   printf("%d\n",strlen(S));
   printf("%d\n",strlen1(S));
   printf("%d\n",strlen2(S));
   printf("%d\n",strlen3(S));
   printf("%d\n",strlen4(S));
   t1 = time(NULL);
   for(i=0;i<N;i++) strlen(S);
   t2 = time(NULL);
   printf("builtin %d\n",t2-t1);
   t1 = time(NULL);
   for(i=0;i<N;i++) strlen1(S);
   t2 = time(NULL);
   printf("special %d\n",t2-t1);
   t1 = time(NULL);
   for(i=0;i<N;i++) strlen2(S);
   t2 = time(NULL);
   printf("simple array %d\n",t2-t1);
   t1 = time(NULL);
   for(i=0;i<N;i++) strlen3(S);
   t2 = time(NULL);
   printf("simple pointer %d\n",t2-t1);
   t1 = time(NULL);
   for(i=0;i<N;i++) strlen4(S);
   t2 = time(NULL);
   printf("my special %d\n",t2-t1);
   return 0;
}
