测量函数运行时间的clock()函数

ゞ 浴缸里的玫瑰 2023-07-09 08:30 7阅读 0赞

clock():捕捉从程序开始运行到clock()被调用时所消耗的时间。这个时间单位是clock tick(时钟打点)
常数CLK_TCK:机器时钟每秒所走的时钟打点数

  1. #include<stdio.h>
  2. #include<time.h>
  3. clock_t start,stop; //clock_t是clock()函数返回的变量类型
  4. double duration; //记录被测函数运行的时间,以秒为单位
  5. void PrintN(int n)
  6. {
  7. int i;
  8. for(i=1;i<=n;i++)
  9. {
  10. printf("%d ",i);
  11. }
  12. }
  13. main()
  14. {
  15. int n;
  16. printf("请输入一个数");
  17. scanf("%d",&n);
  18. start = clock();//开始计时
  19. PrintN(n); //被测的函数
  20. stop = clock();//停止计时
  21. duration = ((double)(stop - start))/CLK_TCK; //计算调用PrintN函数所用的时间
  22. printf("%e",duration); //%e表示数据类型为浮点数,且用科学计算法表示
  23. }

发表评论

表情:
评论列表 (有 0 条评论,7人围观)

还没有评论,来说两句吧...

相关阅读