测试拷贝时间

本文通过三种不同的字符串拷贝方法(纯C语言风格、内联汇编及标准库函数)进行性能测试比较,并展示了每种方法在大量重复操作下的实际执行时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include   <time.h>

  4. void cstrcpy(char *a,char *b);
  5. void  qstrcpy(char * dest,const char *src);

  6. void cstrcpy(char *a,char *b){
  7.     while (*a++ = *b++);
  8. }
  9. void  qstrcpy(char * dest,const char *src)
  10. {
  11. static int d0=0;
  12. static int d1=0;
  13. static int d2=0;
  14. __asm__ __volatile__(
  15.         "1:\tlodsb\n\t"
  16.         "stosb\n\t"
  17.         "testb %%al,%%al\n\t"
  18.         "jne 1b"
  19.         : "=&S" (d0), "=&D" (d1), "=&a" (d2)
  20.         :"0" (src),"1" (dest) : "memory");
  21. }

  22. int main(){
  23.     char a[10];
  24.     char *b="bbbbbbb";
  25.     int i;
  26.     clock_t t_begin;

  27.     i=0;
  28.     t_begin=clock();
  29.     while(i++<10000000){
  30.         cstrcpy(a,b);
  31.     }
  32.     printf("cstrcpy: %lf seconds\n", (double)(clock() - t_begin) / CLOCKS_PER_SEC);

  33.     i=0;
  34.     t_begin=clock();
  35.     while(i++<10000000){
  36.         qstrcpy(a,b);
  37.     }
  38.     printf("qstrcpy: %lf seconds\n", (double)(clock() - t_begin) / CLOCKS_PER_SEC);

  39.     i=0;
  40.     t_begin=clock();
  41.     while(i++<10000000){
  42.         strcpy(a,b);
  43.     }
  44.     printf("strcpy: %lf seconds\n", (double)(clock() - t_begin) / CLOCKS_PER_SEC);
  45. }
复制代码


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

发贴的时候没这样测,是直接在程序里面改函数再计算执行时间的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值