strlen_analyze

周一 01 ε››ζœˆ 2019
By fx-moon
#include <iostream>

#include <vector>

#include <string>

#include <stack>
#include <ctime>
#include <windows.h>

const int n = 1024*1024*500;

using namespace std;
class timer
{
    long long t;

  public:
    timer()
    {
        t = clock();
    }
    ~timer()
    {
        cout << clock() - t << endl;
    }
};
size_t strlen1(const char *str)
{
    register int length = 0;

    while (*str++)

        ++length;

    return (length);
}

size_t strlen3(const char *sstr)
{

    register int length = 0;
    int size = 0;
    int *p_size = &size;
    __asm{
        mov edi,sstr;
        mov ecx,0xffffffff;
        xor eax,eax;
        repne scasb;
        mov eax,dword ptr [p_size];
        mov dword ptr[eax],ecx;
    }
    return 0xffffffff - size -1;
}

size_t strlen2(const char *str)
{

    const char *char_ptr = NULL;

    const unsigned long int *longword_ptr = NULL;

    register unsigned long int longword, magic_bits;

    for (char_ptr = str; ((unsigned long int)(char_ptr)

                          & (sizeof(unsigned long int) - 1)) != 0;
         ++char_ptr)

    {

        if (*char_ptr == '\0')

            return char_ptr - str;
    }

    longword_ptr = (const unsigned long int *)char_ptr;

    magic_bits = 0x7efefeffL;

    for (;;)

    {

        longword = *longword_ptr++;

        if ((((longword + magic_bits) ^ ~longword) & ~magic_bits) != 0)

        {

            const char *cp = (const char *)(longword_ptr - 1);

            if (cp[0] == '\0')

                return cp - str;

            if (cp[1] == '\0')

                return cp - str + 1;

            if (cp[2] == '\0')

                return cp - str + 2;

            if (cp[3] == '\0')

                return cp - str + 3;
        }
    }
}
char s[n]{0};
int main()
{

    for (int i = 0; i < n-1; i++)
        s[i] = 'A';

    {
        timer t;
        cout<<strlen(s)<<' ';
    }
    {
        timer t;
        cout<<strlen1(s)<<' ';
    }
    {
        timer t;
        cout<<strlen2(s)<<' ';
    }
    {
        timer t;
        cout<<strlen3(s)<<' ';
    }
    {
        timer t;
        Sleep(1000);
    }
    system("pause");
    return 0;
}

Pages