在Windows、Unix平台下,拷贝字符串的方法,可以调用strcpy和memcpy两类函数
1)如果srcStr和destStr间没有空间叠加,则可以用memcpy函数,也可以使用strcpy函数
2)如果srcStr和destStr间有空间叠加,则只能用memmove函数
在Windows、Unix上,strcpy和memcpy两类函数的执行效率是不一样的。为了执行效率,memmove通常会使用汇编语言来实现,测试效果发现,使用memmove、strcpy函数比普通的字符串赋值的效率将高6倍,测试程序见附件:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<time.h>
#include<assert.h>
#define STR_LEN 1*1024*1024
int main()
{
int i, j, count=STR_LEN-1;
time_t begintime, endtime;
char *testStr; char *p1, *p2;
testStr = (char*)malloc(STR_LEN);
time( &begintime );
for(j=0; j<1024; j++)
{
/*执行花费时间6秒
for(i=0; i<STR_LEN-1; i++)
testStr[i]=testStr[i+1];
//*/
//*执行花费1秒
strncpy(testStr, testStr+1, STR_LEN-1);
//*/
//*执行花费时间1秒
memmove(testStr, testStr+1, STR_LEN-1);
//*/
}
time( &endtime );
printf("End set int data!! Used time : %ld /n",endtime-begintime);
return 0;
}
字符串拷贝性能对比
本文通过实验比较了在Windows及Unix环境下使用不同函数(如memcpy、strcpy和memmove)进行字符串拷贝的效率。测试表明,使用memmove和strcpy函数相较于普通字符串赋值能提高约6倍的效率。
620

被折叠的 条评论
为什么被折叠?



