- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- void cstrcpy(char *a,char *b);
- void qstrcpy(char * dest,const char *src);
- void cstrcpy(char *a,char *b){
- while (*a++ = *b++);
- }
- void qstrcpy(char * dest,const char *src)
- {
- static int d0=0;
- static int d1=0;
- static int d2=0;
- __asm__ __volatile__(
- "1:\tlodsb\n\t"
- "stosb\n\t"
- "testb %%al,%%al\n\t"
- "jne 1b"
- : "=&S" (d0), "=&D" (d1), "=&a" (d2)
- :"0" (src),"1" (dest) : "memory");
- }
- int main(){
- char a[10];
- char *b="bbbbbbb";
- int i;
- clock_t t_begin;
- i=0;
- t_begin=clock();
- while(i++<10000000){
- cstrcpy(a,b);
- }
- printf("cstrcpy: %lf seconds\n", (double)(clock() - t_begin) / CLOCKS_PER_SEC);
- i=0;
- t_begin=clock();
- while(i++<10000000){
- qstrcpy(a,b);
- }
- printf("qstrcpy: %lf seconds\n", (double)(clock() - t_begin) / CLOCKS_PER_SEC);
- i=0;
- t_begin=clock();
- while(i++<10000000){
- strcpy(a,b);
- }
- printf("strcpy: %lf seconds\n", (double)(clock() - t_begin) / CLOCKS_PER_SEC);
- }
gcc -O3 test.c && ./a.out
cstrcpy: 0.150000 seconds
qstrcpy: 0.150000 seconds
strcpy: 0.180000 seconds
多运行几次后发觉是cstrcpy最快
cstrcpy: 0.110000 seconds
qstrcpy: 0.150000 seconds
strcpy: 0.190000 seconds
发贴的时候没这样测,是直接在程序里面改函数再计算执行时间的。