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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章