C++単純タイマー

2329 ワード

コードセグメントのタイミングを常に必要とするため、以下は抽象的なタイマクラスであり、2つのクラスを含む.1つはTimerクラスであり、タイミング操作に用いられ、タイミングが必要なコードセグメントの開始でStart()を呼び出してタイミングを開始し、コードセグメントの終了でStop()停止計を呼び出すと、Elapse()はコードセグメントの消費時間を取得することができる.もう1つは、TimerFactoryクラスがTimerの管理呼び出しに使用するGetTimer()で、タイマの名前をGetTimer()パラメータで取得できます.
#include 
#include 
#include 
#include 

enum TimeUnit{
    SS = 0, // 
    MS,     //  
    US,     //  
    NS      //  
};

class Timer{
    typedef std::chrono::high_resolution_clock hrc;
    typedef std::chrono::time_point<:chrono::high_resolution_clock>  tp_hrc;
public:
    Timer():start_(hrc::now()),end_(hrc::now()){}
    virtual ~Timer(){}

    void Start(){
        start_ = hrc::now();
    }
    void Stop(){
        end_ = hrc::now();
    }
    void Reset(){
        start_ = hrc::now();
        end_ = hrc::now();
    }
    double Elapsed(TimeUnit type = MS){
        if(type == TimeUnit::SS){
            return std::chrono::duration_cast<:chrono::seconds>(end_ - start_).count();
        }else if(type == TimeUnit::MS){
            return std::chrono::duration_cast<:chrono::milliseconds>(end_ - start_).count();
        }else if(type == TimeUnit::US){
            return std::chrono::duration_cast<:chrono::microseconds>(end_ - start_).count();
        }else if(type == TimeUnit::NS){
            return std::chrono::duration_cast<:chrono::nanoseconds>(end_ - start_).count();
        }
    }

private:
    tp_hrc start_;
    tp_hrc end_;
};//end Timer

class TimerFactory{
public:
    TimerFactory(){}
    virtual ~TimerFactory(){
        if(!timers_.empty()){
            timers_.clear();
        }
    }

    std::shared_ptr GetTimer(const std::string& name){
        if(timers_.find(name) != timers_.end()){
            return timers_[name];
        }else{
            timers_[name] = std::make_shared();
            return timers_[name];
        }
    }
private:
    std::map<:string> > timers_;
}; //end TimerFactory

int main(){
    Timer timer;
    timer.Start();
    sleep(1);
    timer.Stop();
    std::cout<