C++代码块执行时间
时间: 2024-01-11 10:20:25 浏览: 126
以下是两种C++计算代码块执行时间的方法:
1.使用clock()函数计算代码块执行时间
```cpp
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t start, finish;
double time_length;
start = clock(); // 记录开始时间
// 代码块
for (int i = 0; i < 100000000; i++) {
// Do something
}
finish = clock(); // 记录结束时间
time_length = (double)(finish - start) / CLOCKS_PER_SEC; // 计算代码块执行时间
cout << "Time used is " << time_length << " second." << endl;
return 0;
}
```
2.使用自定义计时器类计算代码块执行时间
```cpp
#include <iostream>
#include <chrono>
using namespace std;
class Timer {
public:
Timer() {
m_StartTimepoint = chrono::high_resolution_clock::now();
}
~Timer() {
Stop();
}
void Stop() {
auto endTimepoint = chrono::high_resolution_clock::now();
auto start = chrono::time_point_cast<chrono::microseconds>(m_StartTimepoint).time_since_epoch().count();
auto end = chrono::time_point_cast<chrono::microseconds>(endTimepoint).time_since_epoch().count();
auto duration = end - start;
double ms = duration * 0.001;
cout << "Time used is " << ms << " ms." << endl;
}
private:
chrono::time_point<chrono::high_resolution_clock> m_StartTimepoint;
};
int main() {
{
Timer timer;
// 代码块
for (int i = 0; i < 100000000; i++) {
// Do something
}
}
return 0;
}
```
阅读全文