需要包含的头文件及类实现:
#include <chrono>
#include <thread>
class Timer {
public:
Timer() : m_StartTimepoint(std::chrono::high_resolution_clock::now()) {}
~Timer() {
Stop();
}
void Stop() {
auto endTimepoint = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::nanoseconds>(m_StartTimepoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::nanoseconds>(endTimepoint).time_since_epoch().count();
auto duration = end - start;
double ms = duration * 1.0e-6;
std::cout << duration << "ns (" << ms << "ms)\n";
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTimepoint;
};
使用:
int main() {
//第一个示例
{
printf("test1\n");
Timer timer;
// 你需要计时的代码
for (int i = 0; i < 100; i++) {
std::cout << "Hello, World!\n";
}
}
//第二个示例
{
printf("test2\n");
Timer timer;
//std::this_thread::sleep_for(std::chrono::seconds(3)); //休眠三秒
std::this_thread::sleep_for(std::chrono::milliseconds(100)); //休眠100毫秒
}
return 0;
}
结果: