Timer是一个辅助函数,用于程序计时。它封装了STL中的chrono。
只要把chrono中的时钟、时间点和时间间隔看懂,下面的代码就是小菜一碟。
#pragma once
//STL
#include <chrono>
namespace StVO {
class Timer {
public:
// Timer的时间单位:秒 毫秒 纳秒
static constexpr double SECONDS = 1e-9;
static constexpr double MILLISECONDS = 1e-6;
static constexpr double NANOSECONDS = 1.0;
Timer(double scale = MILLISECONDS); // 默认构造,单位为毫秒
virtual ~Timer();
void start();
double stop();
private:
// 采用高分辨率时钟,定义了一个时间点类型
std::chrono::high_resolution_clock::time_point start_t;
bool started;
double scale;
};
} // namespace StVO
#include "timer.h"
//STL
#include <stdexcept>
#include <chrono>
namespace StVO {
Timer::Timer(double scale) : started(false), scale(scale) { }
Timer::~Timer() { }
void Timer::start() {
started = true;
start_t = std::chrono::high_resolution_clock::now();
}
// 在timer stop的时候,直接输出了duration
double Timer::stop() {
// 写成 auto end_t = ... 多好!
std::chrono::high_resolution_clock::time_point end_t = std::chrono::high_resolution_clock::now();
if (!started)
throw std::logic_error("[Timer] Stop called without previous start");
started = false;
std::chrono::duration<double, std::nano> elapsed_ns = end_t - start_t;
return elapsed_ns.count()*scale;
}
} // namespace StVO