본문 바로가기

C++/STL

chrono 타이머

[1. 개요]

C++ 애플리케이션 작성 시, 여러가지 타이머 관련 예제 정리


[2. 예제]

#include <iostream>
#include <chrono>
#include <thread>
#include <ctime>
void wait()
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(2000ms);
}
int main()
{
{
// 1970-01-01 로 부터 경과한 초.
const auto beg = std::time(nullptr);
wait();
const auto end = std::time(nullptr);
std::cout << "Wait time " << (end - beg) << " sec\n";
}
{
// 프로그램이 실행된 후 CPU가 사용한 시간(클럭 틱 수)
const auto beg = std::clock();
wait();
const auto end = std::clock();
std::cout << "[1]Wait time " << (end - beg) << " msec\n";
std::cout << "[2]Wait time " << (end - beg) / CLOCKS_PER_SEC << " sec\n";
}
{
// system_clock: 시스템의 현재 시간, 시간이 변할 수 있음.
const auto beg = std::chrono::system_clock::now();
wait();
const auto end = std::chrono::system_clock::now();
const auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end-beg).count();
std::cout << "Wait time " << duration << " usec\n";
}
{
// steady_clock: 일관된 시간 측정, 시간이 변하지 않음.
const auto beg = std::chrono::steady_clock::now();
wait();
const auto end = std::chrono::steady_clock::now();
const auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-beg).count();
std::cout << "Wait time " << duration << " nsec\n";
}
return 0;
}
view raw timer.cpp hosted with ❤ by GitHub

 

'C++ > STL' 카테고리의 다른 글

erase 계열 함수...  (0) 2025.02.11
map 과 unordered_map 의 차이점.  (0) 2024.10.23
set vs multiset  (0) 2024.08.31
priority_queue  (0) 2022.09.08