如何在 C 中计算函数花费的时间?
在这里,我们将了解如何计算该进程花费的时间。对于此问题,我们将使用 clock() 函数。time.h 头文件中有 clock()。
为了获得经过时间,我们可以在开始时和任务结束时使用 clock() 来获取时间,然后减去这些值以获得差异。在此之后,我们将该差异除以 CLOCK_PER_SEC(每秒时钟滴答数)以获取处理器时间。
示例
#include <stdio.h> #include <time.h> 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 starts Press enter to stop the counter Timer ends The program took 5.218000 seconds to execute
广告