- 论坛徽章:
- 0
|
你这种做法明显是错误的,你对sprintf程序做了优化,但是strcat程序却没有优化
strcat的时候,每次都要找到src的结尾,然后再拼接,这样的话时间花在找到src的长度上
而你的sprintf程序确是每次给p直接指向结尾,这样就不需要找到长度
如果公平,你应该用sprintf(p, "%s|%s", p, a)
或者改进一下strcat程序
cat test.c ;gcc test.c -o 1; gcc -DSTR test.c -o 2;time ./1 ; time ./2
#include<stdio.h>
#include<string.h>
int main()
{
int i,j;
char a[] = "abcdwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww";
char buf[50000];
char *p;
int len = 0;
int len1 = strlen( a );
int len2 = strlen( "|" );
for( i = 0; i < 0xfffff; i++ )
{
buf[0] = 0;
p=buf;
for(j=0;j<50;j++) {
#ifdef STR
strcat(p,a);
p += len1;
strcat(p,"|");
p += len2;
#else
p+=sprintf( p, "%s|", a);
#endif
}
}
return 0;
}
real 0m8.432s
user 0m8.431s
sys 0m0.000s
real 0m2.780s
user 0m2.778s
sys 0m0.002s
|
[ 本帖最后由 deadlylight 于 2009-10-14 11:05 编辑 ] |
|