如何测量C函数所花费的时间?
在这里,我们将看到如何计算过程花费的时间。对于此问题,我们将使用clock()函数。clock()存在于time.h头文件中。
要获得经过的时间,我们可以在任务的开始和结束时使用clock()来获取时间,然后减去这些值以获得差值。之后,我们将差异除以CLOCK_PER_SEC(每秒的时钟滴答数)以获得处理器时间。
示例
#include <stdio.h>
#include <time.h>
void take_enter() {
printf("Press enter to stop the counter \n");
while(1) {
if (getchar())
break;
}
}
main() {
// Calculate the time taken by take_enter()
clock_t t;
t = clock();
printf("Timer starts\n");
take_enter();
printf("Timer ends \n");
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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短