C++利用RAII特性,实现一个Timer
#include <string>
#include <chrono>
#include <iostream>
class Timer {
public:
Timer(const std::string& task = "Unnamed task") :
task(task),
start(std::chrono::high_resolution_clock::now()) {}
~Timer()
{
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = end - start;
std::cout << task << " elapsed " << elapsed.count() << " ms.\n";
}
private:
std::string task;
std::chrono::time_point<std::chrono::high_resolution_clock> start;
};
执行Timer
int main()
{
{
Timer t("TestFunc");
TestFunc();
}
}
执行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/45daf956e851491eb01f8fb923ae28ee.png)