Measure C Program Execution Time
In the C language, the program’s running time can be measured using the clock() function in the time.h header file. The specific steps are as follows:
- Firstly, the time.h header file needs to be included.
#include <time.h>
- Call the clock() function at the beginning of the program to obtain the clock time when the program starts executing.
clock_t start = clock();
- Call the clock() function at the end of the program to obtain the clock time when the program finishes execution.
clock_t end = clock();
- Calculate the running time of the program. The clock() function returns the number of clock cycles, which need to be divided by CLOCKS_PER_SEC to get the running time in seconds.
double elapsed_time = (double)(end - start) / CLOCKS_PER_SEC;
The complete example code is as follows:
#include <stdio.h>
#include <time.h>
int main() {
clock_t start = clock();
// 程序逻辑代码
clock_t end = clock();
double elapsed_time = (double)(end - start) / CLOCKS_PER_SEC;
printf("程序运行时间:%f秒\n", elapsed_time);
return 0;
}
The above code will output the program’s running time in seconds.