gpt4 book ai didi

c - 我的 strchr() 比原来的 Visual Studio 2015 慢

转载 作者:行者123 更新时间:2023-11-30 20:54:56 24 4
gpt4 key购买 nike

strchr() 。我认为它与 VS 2015 中的实现相同。我将其复制到一个新函数中并尝试了。我对一个字符有很大的不同array[15001767] (存储在堆中),原始 3 毫秒,我的 17 毫秒。

这个差异在哪里?

char *teststr(const char *s, int c)
{
while (*s != (char)c)
if (!*s++)
return 0;
return (char *)s;
}

int main()
{
DWORD pa;

char *test = (char*)HeapAlloc(HeapCreate(NULL, 0, 0), NULL, 15001767);
ReadFile(CreateFileW(L"MyFile.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, NULL, NULL), test, 15001767, &pa, NULL);

//strchr(test, '£');
teststr(test, '£');

}

最佳答案

您可能对我使用标准库 (MSVC)、OP 函数和两个汇编器版本(其中之一被告知字符串长度)构建的不同 strchr 实现的比较感兴趣,另一个必须先找到它。第二个仍然比 OP 的例程快。

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

#define LEN 15001767
#define REPS 100

char array[LEN];

char *asmstrchrA(const char *s, int c)
// knows the string length
{
__asm {
push es
mov ax,ds
mov es,ax
mov edi,s
mov ecx,LEN
mov eax,c
cld
repne scasb
jz foundA
xor edi,edi ; not found
inc edi
foundA:
dec edi
mov s,edi
pop es
}
return (char *)s;
}

char *asmstrchrB(const char *s, int c)
// finds the string length first
{
__asm {
push es
mov ax,ds
mov es,ax

mov edi,s ; find string length
xor eax,eax
mov ecx,-1
cld
repne scasb
mov ecx,edi
sub ecx,s

mov edi,s ; find char
mov eax,c
cld
repne scasb
jz foundB
xor edi,edi ; not found
inc edi
foundB:
dec edi
mov s,edi
pop es
}
return (char *)s;
}

char *OPstrchr(const char *s, int c)
// from OP's link
{
while (*s != (char)c)
if (!*s++)
return 0;
return (char *)s;
}

int main (void) {
clock_t start;
int i;
char * cptr;

memset(array, '1', LEN-1);
array[LEN-5] = '2';

start = clock();
for(i=0; i<REPS; i++)
cptr = OPstrchr(array, '2');
printf("OPstrchr %p, time = %f seconds\n", (void*)cptr, (double)(clock() - start) / CLOCKS_PER_SEC);

start = clock();
for(i=0; i<REPS; i++)
cptr = asmstrchrA(array, '2');
printf("asmstrchrA %p, time = %f seconds\n", (void*)cptr, (double)(clock() - start) / CLOCKS_PER_SEC);

start = clock();
for(i=0; i<REPS; i++)
cptr = asmstrchrB(array, '2');
printf("asmstrchrB %p, time = %f seconds\n", (void*)cptr, (double)(clock() - start) / CLOCKS_PER_SEC);

start = clock();
for(i=0; i<REPS; i++)
cptr = strchr(array, '2');
printf("strchr %p, time = %f seconds\n", (void*)cptr, (double)(clock() - start) / CLOCKS_PER_SEC);
return 0;
}

程序输出:

OPstrchr   0125F5A2, time = 7.488000 seconds
asmstrchrA 0125F5A2, time = 1.248000 seconds
asmstrchrB 0125F5A2, time = 2.512000 seconds
strchr 0125F5A2, time = 1.045000 seconds

关于c - 我的 strchr() 比原来的 Visual Studio 2015 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36161046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com