在这里,我们将看到如何计算进程所花费的时间。对于这个问题,我们将使用clock()函数。clock()函数位于time.h头文件中。
要获取经过的时间,我们可以在任务开始时使用clock()获取时间,在任务结束时再次使用clock()获取时间,然后将这两个值相减得到差值。然后,我们将差值除以CLOCK_PER_SEC(每秒钟的时钟滴答数)以获取处理器时间。
示例
#include #include void take_enter() { printf("Press enter to stop the counter"); while(1) { if (getchar()) break; }}main() { // Calculate the time taken by take_enter() clock_t t; t = clock(); printf("Timer starts
"); take_enter(); printf("Timer ends
"); 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 startsPress enter to stop the counterTimer endsThe program took 5.218000 seconds to execute
登录后复制
以上就是如何在C语言中测量函数的执行时间?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2585608.html