在性能关键型应用中,我们经常需要对代码的执行时间进行精确度到纳秒级别的测量。C++11 为我们提供了一个强大的工具——std::chrono 库,它可以帮助我们创建一个高精度计时器。
以下是一个使用 std::chrono 创建的纳秒级计时器的示例,并对其进行了详细的介绍。
#include <chrono>
#include <iostream>
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