#include <iostream>
#include <windows.h>
#include <chrono>
/* 模板实现: 编译期就确定了, 需要传入编译期即可确定的字符数组, 可能没什么意义... */
template<typename T, size_t N>
size_t length(T(&)[N])
{
return N - 1;
}
/*
\主要使用指令 repne scasb, 如果使用repne scasd应该能更快
*/
__declspec(naked) DWORD WINAPI StringLength1(LPCSTR pszStr)
{
__asm
{
push ebp
mov ebp, esp
or ecx, 0xffffffff
mov edi, [ebp+8]
xor eax, eax
test edi, edi
jz _fexit
repne scasb
not ecx
mov eax, ecx
dec eax
_fexit:
leave
retn 4
}
}
/*
\常规实现
*/
DWORD StringLength2(LPCSTR pszStr)
{
if (NULL == pszStr)
return 0;
DWORD dwCnt = 0;
while (*pszStr++)
++dwCnt;
return dwCnt;
}
// MAIN
int main(int, char **)
{
// 十亿个字符
char* test =
计算字符串长度[C++/ASM]
于 2018-10-20 00:03:35 首次发布