zheng614

博客园 首页 联系 订阅 管理
 

在很多时候,我们都会使用的strcpy这个函数,我们跟踪c语言库的话,会发现它是用汇编写的。按道理来说效率应该很高,但是我写了几个strcpy的函数测试了一下:

char *strcpy1(char *dest, const char *src)
{
int i = 0;

while (src[i])
dest[i++] = src[i];

dest[i] = '';
return dest;
}

这个是一般的做法,我想大家都能想到。


char *strcpy2(char *dest, const char *src)
{
char *p = dest;

while (*src)
*dest++ = *src++;

*dest = '';
return p;
}

strcpy2
的优点是少了一个变量i,可以少一个运算。


char *strcpy3(char *dest, const char *src) {
const char *end = src;
while (*end)
end++;
memcpy(dest, src, end-src+1);
return dest;
}

这个是我自己写的,也是要推荐了,要知道mencpy的效率要比按字节拷贝快的多的多。

下面我们用代码来测试一下效率:

#include <malloc.h>
#include <STRING.h>
#include <windows.H>
#include <STDIO.H>

void main()
{
long nSize = 200;
char* pSource = (char *)malloc(nSize+1);
char* pDest = (char *)malloc(nSize+1);
memset(pSource, 'a', nSize);
pSource[nSize] = '';

DWORD dwStart = GetTickCount();
for(int i=0; i<5000000; i++)
{
strcpy(pDest, pSource);
}
DWORD dwEnd = GetTickCount();

printf("%d", dwEnd-dwStart);
}

我们分两块测试,第一块是小段字符串拷贝,如上面的200个字节。然后我们测试一下10M字节的,当然循环次数只用100次就够了。

release
下测试结果如下:

函数 20字节 200字节 10M

strcpy 3734 1734 2265

strcpy1 2015 1391 4219

strcpy2 1953 1453 3937

strcpy3 2422 984 1890

所以说c标准库的不一定是最快的。

最后请大家在debug下跑一下看看,你会有新的惊喜,反正我还没有搞清楚是为什么。

posted on 2006-04-02 13:54  人海中一片孤云  阅读(1975)  评论(1编辑  收藏  举报