//
//                         UtilTimer.h
//
#include <sys/time.h>

#ifndef UTILTIMER_H
#define UTILTIMER_H

inline double subtime(const timeval &a, const timeval &b)
{
    if (a.tv_usec >= b.tv_usec)
        return (a.tv_sec - b.tv_sec) * 1.0 + (a.tv_usec - b.tv_usec) * 1e-6;
    else
        return (a.tv_sec - b.tv_sec - 1) * 1.0 + (a.tv_usec - b.tv_usec + 1000000) * 1e-6;
}

class UtilTimer {
public:
    UtilTimer() { start();}
    void start(){ 
        gettimeofday(&m_start_time, NULL);
        m_current_time = m_start_time;
    }
    std::string get_starttime(){ 
        struct tm *tm_p;
        char date[32];

        gettimeofday(&m_start_time, NULL);
        tm_p = (struct tm *)localtime((time_t *)&m_start_time.tv_sec);
        sprintf(date,"%04d%02d%02d_%02d:%02d:%02d",tm_p->tm_year+1900,tm_p->tm_mon+1,tm_p->tm_mday,tm_p->tm_hour,tm_p->tm_min,tm_p->tm_sec);
        std::string result(date);
        return result;
    }
    double tick(){
        struct timeval pre = m_current_time;
        gettimeofday(&m_current_time, NULL);
        return subtime(m_current_time, pre);
    }
    double time(){ 
        gettimeofday(&m_current_time, NULL);
        return subtime(m_current_time, m_start_time);
    }

    timeval current(){
        struct timeval ctime;;
        gettimeofday(&ctime, NULL);
        return ctime;
    }
    
  private:
    struct timeval m_start_time;
    struct timeval m_current_time;
};

#endif //UTILTIMER_H
