
在这里,我们将看到如何计算进程所花费的时间。对于这个问题,我们将使用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中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号