要测试C语言代码的执行时间,你可以使用标准库 <time.h> 中的 clock() 函数。这个函数返回从程序启动开始已经花费的CPU时钟周期数。然后你可以将得到的时钟周期数转换为秒或毫秒以获得执行时间。
#include <stdio.h>
#include <time.h>
int main()
{
clock_t start, end;
double cpu_time_used;
// 记录开始时间
start = clock();
// 在这里可以添加一些代码来进行时间测试
for (int i = 0; i < 10000000; i++)
{
// do something
}
// 记录结束时间
end = clock();
// 计算执行时间(秒)
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("执行时间:%f 秒\n", cpu_time_used);
return 0;
}
封装成函数
#include <stdio.h>
#include <time.h>
// 要测试的函数
void my_function() {
// 模拟函数执行
for (int i = 0; i < 10000000; i++) {
// do something
}
}
// 计算函数执行时间
void calculate_function_runtime(void (*function)()) {
clock_t start_time = clock(); // 记录函数开始时间
function(); // 调用函数
clock_t end_time = clock(); // 记录函数结束时间
double runtime_seconds = (double)(end_time - start_time) / CLOCKS_PER_SEC; // 计算函数执行时间(秒)
printf("函数执行时间:%f 秒\n", runtime_seconds);
}
int main() {
// 调用 calculate_function_runtime() 函数来计算 my_function() 函数的执行时间
calculate_function_runtime(my_function);
return 0;
}
借用工具
vscode编辑器中,代码用code runner运行,结束后会输出
[Done] exited with code=0 in 0.152 seconds