首页 > 后端开发 > C++ > 正文

如何在C语言中测量函数的执行时间?

WBOY
发布: 2023-08-28 14:21:06
转载
964 人浏览过

如何在C语言中测量函数的执行时间?

在这里,我们将看到如何计算进程所花费的时间。对于这个问题,我们将使用clock()函数。clock()函数位于time.h头文件中。

要获取经过的时间,我们可以在任务开始时使用clock()获取时间,在任务结束时再次使用clock()获取时间,然后将这两个值相减得到差值。然后,我们将差值除以CLOCK_PER_SEC(每秒钟的时钟滴答数)以获取处理器时间。

示例

#include <stdio.h>
#include <time.h>
void take_enter() {
   printf("Press enter to stop the counter </p><p>");
   while(1) {
      if (getchar())
      break;
   }
}
main() {
   // Calculate the time taken by take_enter()
   clock_t t;
   t = clock();
   printf("Timer starts</p><p>");
   take_enter();
   printf("Timer ends </p><p>");
   t = clock() - t;
   double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
   printf("The program took %f seconds to execute", time_taken);
}
登录后复制

输出

Timer starts
Press enter to stop the counter
Timer ends
The program took 5.218000 seconds to execute
登录后复制

以上是如何在C语言中测量函数的执行时间?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!