본문 바로가기
💻 programming/c++

[c++] timer 클래스 만들기

by 연구원-A 2021. 8. 4.
반응형

chrono 라이브러리를 이용해서 타이머 클래스를 만들어봅시다.

#include <chrono>
#include <string>
#include <iostream>
#include <thread>

typedef std::chrono::steady_clock sclock;

//@brief Timer measure time diff between start() and stop()
class Timer {
  public:
    virtual ~Timer() { }
    inline void start() { start_time = sclock::now(); }
    inline void stop()  { end_time = sclock::now(); }

    inline double elapsed_milli() const
    { return std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); }

    inline double elapsed_sec() const
    { return elapsed_milli() / 1000.0; }

  private:
    sclock::time_point start_time;
    sclock::time_point end_time;
};

int main() {

    Timer timer;
    timer.start();
    for(int i = 0 ; i < 2; i++)
        std::this_thread::sleep_for(std::chrono::seconds(1));
    timer.stop();
    std::cout << timer.elapsed_milli() << " (ms)" << std::endl;
    std::cout << timer.elapsed_sec() << " (s)" << std::endl;

}
반응형

'💻 programming > c++' 카테고리의 다른 글

[c++] fold expression  (0) 2021.08.05
[c++] logger 클래스 만들기  (0) 2021.08.04
[c++] thread vs task (thread 와 async)  (0) 2021.08.04
[c++] thread  (0) 2021.08.04
[c++] lvalue reference and rvalue reference  (0) 2021.08.04

댓글