要获取经过的时间,我们可以在任务开始时使用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 startspress enter to stop the countertimer endsthe program took 5.218000 seconds to execute
以上就是如何在c语言中测量函数的执行时间?的详细内容。
