> 文章列表 > c语言计算程序运行时间

c语言计算程序运行时间

c语言计算程序运行时间

在C语言中,计算程序运行时间可以通过以下几种方法:

1. 使用 `clock()` 函数:

```c#include int main() { clock_t start = clock(); // 获取程序开始时的时钟周期数 // 程序代码 clock_t end = clock(); // 获取程序结束时的时钟周期数 double cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC; // 计算运行时间 printf(\"程序运行时间:%f 秒\\n\", cpu_time_used); return 0;}```

2. 使用 `gettimeofday()` 函数:

```c#include #include void function() { // 程序代码}int main() { struct timeval tpstart, tpend; gettimeofday(&tpstart, NULL); // 记录程序开始时间 function(); // 程序代码 gettimeofday(&tpend, NULL); // 记录程序结束时间 double timeused = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_usec - tpstart.tv_usec); timeused /= 1000000; // 转换为秒 printf(\"程序运行时间:%f 秒\\n\", timeused); return 0;}```

3. 使用 `std::chrono`(C++):

```cpp#include #include int main() { auto start = std::chrono::high_resolution_clock::now(); // 记录程序开始时间 // 程序代码 auto end = std::chrono::high_resolution_clock::now(); // 记录程序结束时间 double elapsed_secs = std::chrono::duration_cast<std::chrono::duration>(end - start).count(); // 计算运行时间 std::cout << \"Elapsed time: \" << elapsed_secs << \" seconds.\" << std::endl; return 0;}```

以上方法可以帮助你计算C语言程序的运行时间。请选择适合你需求的方法进行使用

其他小伙伴的相似问题: