C++ Chrono 완벽 가이드 | "시간" 라이브러리 완벽 가이드
이 글의 핵심
C++ Chrono에 대해 정리한 개발 블로그 글입니다. #include <chrono> #include <iostream> using namespace std; using namespace chrono;
기본 사용법
#include <chrono>
#include <iostream>
using namespace std;
using namespace chrono;
int main() {
// 시간 측정
auto start = high_resolution_clock::now();
// 작업
for (int i = 0; i < 1000000; i++) {
// ...
}
auto end = high_resolution_clock::now();
// 경과 시간
auto duration = duration_cast<milliseconds>(end - start);
cout << "시간: " << duration.count() << "ms" << endl;
}
Duration
// 다양한 단위
seconds sec(5);
milliseconds ms(5000);
microseconds us(5000000);
nanoseconds ns(5000000000);
// 변환
auto ms2 = duration_cast<milliseconds>(sec);
cout << ms2.count() << "ms" << endl; // 5000
// 산술 연산
auto total = 1s + 500ms; // 1500ms
auto half = 1s / 2; // 500ms
Time Point
// 현재 시간
auto now = system_clock::now();
// 시간 더하기
auto future = now + hours(24);
// 시간 빼기
auto past = now - minutes(30);
// 시간 차이
auto diff = future - now;
cout << duration_cast<hours>(diff).count() << "시간" << endl;
실전 예시
예시 1: 벤치마크
template<typename Func>
void benchmark(const string& name, Func func) {
auto start = high_resolution_clock::now();
func();
auto end = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(end - start);
cout << name << ": " << duration.count() << "μs" << endl;
}
int main() {
benchmark("벡터 push_back", {
vector<int> v;
for (int i = 0; i < 10000; i++) {
v.push_back(i);
}
});
benchmark("벡터 reserve", {
vector<int> v;
v.reserve(10000);
for (int i = 0; i < 10000; i++) {
v.push_back(i);
}
});
}
예시 2: 타이머
class Timer {
private:
time_point<high_resolution_clock> start;
public:
Timer() : start(high_resolution_clock::now()) {}
void reset() {
start = high_resolution_clock::now();
}
double elapsed() const {
auto end = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(end - start);
return duration.count();
}
void print(const string& msg) const {
cout << msg << ": " << elapsed() << "ms" << endl;
}
};
int main() {
Timer timer;
// 작업 1
this_thread::sleep_for(100ms);
timer.print("작업 1");
// 작업 2
this_thread::sleep_for(200ms);
timer.print("작업 2");
}
예시 3: 타임아웃
bool waitForCondition(function<bool()> condition, milliseconds timeout) {
auto start = steady_clock::now();
while (!condition()) {
auto now = steady_clock::now();
if (now - start > timeout) {
return false; // 타임아웃
}
this_thread::sleep_for(10ms);
}
return true; // 성공
}
int main() {
bool ready = false;
thread worker([&]() {
this_thread::sleep_for(500ms);
ready = true;
});
if (waitForCondition([&]() { return ready; }, 1s)) {
cout << "완료" << endl;
} else {
cout << "타임아웃" << endl;
}
worker.join();
}
예시 4: 프레임 레이트 제어
class FrameRateController {
private:
duration<double> targetFrameTime;
time_point<steady_clock> lastFrame;
public:
FrameRateController(int fps)
: targetFrameTime(1.0 / fps),
lastFrame(steady_clock::now()) {}
void wait() {
auto now = steady_clock::now();
auto elapsed = now - lastFrame;
if (elapsed < targetFrameTime) {
this_thread::sleep_for(targetFrameTime - elapsed);
}
lastFrame = steady_clock::now();
}
double getFPS() const {
auto now = steady_clock::now();
auto elapsed = duration_cast<duration<double>>(now - lastFrame);
return 1.0 / elapsed.count();
}
};
int main() {
FrameRateController frc(60); // 60 FPS
for (int i = 0; i < 600; i++) {
// 게임 로직
frc.wait();
if (i % 60 == 0) {
cout << "FPS: " << frc.getFPS() << endl;
}
}
}
시계 종류
// system_clock: 시스템 시간 (조정 가능)
auto sys = system_clock::now();
// steady_clock: 단조 증가 (타이머용)
auto steady = steady_clock::now();
// high_resolution_clock: 최고 정밀도
auto high = high_resolution_clock::now();
시간 변환
// time_t로 변환
auto now = system_clock::now();
time_t tt = system_clock::to_time_t(now);
// 출력
cout << ctime(&tt) << endl;
// time_t에서 변환
time_t tt2 = time(0);
auto tp = system_clock::from_time_t(tt2);
리터럴 (C++14)
using namespace chrono_literals;
auto d1 = 5s; // 5초
auto d2 = 100ms; // 100밀리초
auto d3 = 2min; // 2분
auto d4 = 1h; // 1시간
auto total = 1h + 30min + 45s;
cout << duration_cast<seconds>(total).count() << "초" << endl;
자주 발생하는 문제
문제 1: 시계 선택
// ❌ system_clock (시간 조정 시 문제)
auto start = system_clock::now();
// 시스템 시간 변경
auto end = system_clock::now();
// 음수 duration 가능!
// ✅ steady_clock (타이머용)
auto start = steady_clock::now();
// ...
auto end = steady_clock::now();
// 항상 양수
문제 2: duration_cast 손실
// ❌ 정밀도 손실
auto ns = 1500ns;
auto ms = duration_cast<milliseconds>(ns);
cout << ms.count() << endl; // 1 (500ns 손실)
// ✅ 손실 인지
auto ns = 1500ns;
auto ms = duration_cast<milliseconds>(ns);
auto remainder = ns - ms;
cout << ms.count() << "ms + " << remainder.count() << "ns" << endl;
문제 3: 오버플로우
// ❌ 오버플로우
auto big = hours(INT_MAX);
auto bigger = big + hours(1); // 오버플로우
// ✅ 적절한 타입
auto big = duration<long long, ratio<3600>>(INT_MAX);
성능 측정
class Profiler {
private:
map<string, duration<double>> timings;
time_point<high_resolution_clock> start;
string currentSection;
public:
void begin(const string& section) {
currentSection = section;
start = high_resolution_clock::now();
}
void end() {
auto end = high_resolution_clock::now();
timings[currentSection] += duration_cast<duration<double>>(end - start);
}
void report() {
for (const auto& [section, time] : timings) {
cout << section << ": " << time.count() << "s" << endl;
}
}
};
int main() {
Profiler profiler;
profiler.begin("초기화");
this_thread::sleep_for(100ms);
profiler.end();
profiler.begin("처리");
this_thread::sleep_for(200ms);
profiler.end();
profiler.report();
}
FAQ
Q1: chrono는 언제 사용하나요?
A:
- 시간 측정
- 타이머
- 벤치마크
- 프레임 레이트 제어
Q2: 어떤 시계를 사용하나요?
A:
- steady_clock: 타이머, 벤치마크
- system_clock: 실제 시간
- high_resolution_clock: 최고 정밀도
Q3: 성능 오버헤드는?
A: 매우 적습니다. 시스템 콜 한 번 정도.
Q4: 정밀도는?
A: 플랫폼에 따라 다르지만 보통 나노초 수준.
Q5: 스레드 안전한가요?
A: now() 호출은 안전합니다.
Q6: Chrono 학습 리소스는?
A:
- cppreference.com
- “C++11/14/17 Features”
- “The C++ Standard Library”
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Chrono | “시간 라이브러리” 가이드
- C++ steady_clock | “안정 시계” 가이드
- C++ duration | “시간 간격” 가이드
관련 글
- C++ Chrono 상세 가이드 |
- C++ duration |
- C++ ratio |
- C++ steady_clock |
- C++ time_point |