Timer类

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值