c++ 计时
时间: 2023-06-28 14:04:05 浏览: 51
你可以使用 `chrono` 库来进行计时,具体步骤如下:
1. 引入头文件 `#include <chrono>`
2. 定义时间点类型 `using namespace std::chrono;`
3. 获取开始时间 `auto start = high_resolution_clock::now();`
4. 获取结束时间 `auto stop = high_resolution_clock::now();`
5. 计算时间差 `auto duration = duration_cast<microseconds>(stop - start);`
6. 输出时间差 `std::cout << "Time taken by function: " << duration.count() << " microseconds" << std::endl;`
完整示例代码如下:
```c++
#include <iostream>
#include <chrono>
using namespace std::chrono;
void myFunction() {
// 一些耗时的操作
}
int main() {
auto start = high_resolution_clock::now();
myFunction();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
std::cout << "Time taken by function: " << duration.count() << " microseconds" << std::endl;
return 0;
}
```
这里使用 `microseconds` 作为时间单位,你可以根据需要使用其他时间单位,例如 `milliseconds`、`seconds` 等。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)