C++ time_point | "Time Points" Guide

C++ time_point | "Time Points" Guide

이 글의 핵심

std::chrono::time_point represents a point in time on a specific clock. It is used with duration, and the resolution can be changed with time_point_cast in time conversion, and when measuring elapsed time in a stopwatch or benchmark, the reference point is set with now().

What is time_point?

std::chrono::time_point represents a point in time above a specific clock. It is used with duration, and the resolution can be changed with time_point_cast in time conversion, and when measuring elapsed time in stopwatch·benchmark, the reference point is set with now().```cpp #include

auto now = std::chrono::system_clock::now(); auto epoch = std::chrono::system_clock::time_point{}; ## Default usecpp using namespace std::chrono;

// 현재 시간 auto now = system_clock::now();

// epoch 이후 시간 auto duration = now.time_since_epoch(); auto ms = duration_cast(duration);

std::cout << ms.count() << “ms” << std::endl; How ​​it works: `time_point` stores duration from epoch. The epoch of `system_clock` is usually 1970-01-01 00:00:00 UTC.cpp // time_point 구조 (개념적) template<typename Clock, typename Duration> class time_point { Duration d_; // epoch로부터의 duration public: Duration time_since_epoch() const { return d_; } };


### Example 1: Measuring time```cpp
auto start = std::chrono::steady_clock::now();

// 작업
std::this_thread::sleep_for(std::chrono::seconds(1));

auto end = std::chrono::steady_clock::now();
auto elapsed = end - start;

auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
std::cout << "경과: " << ms.count() << "ms" << std::endl;
```### Example 2: Timestamp```cpp
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);

std::cout << "타임스탬프: " << timestamp << std::endl;
std::cout << "시간: " << std::ctime(&timestamp);
```### Example 3: Future time```cpp
using namespace std::chrono;

auto now = system_clock::now();
auto future = now + hours(24);  // 24시간 후

auto futureTime = system_clock::to_time_t(future);
std::cout << "24시간 후: " << std::ctime(&futureTime);
```### Example 4: Time comparison```cpp
auto t1 = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
auto t2 = std::chrono::system_clock::now();

if (t2 > t1) {
    std::cout << "t2가 나중" << std::endl;
}

auto diff = t2 - t1;
```## Clock type```cpp
// system_clock: 시스템 시간
auto sys = std::chrono::system_clock::now();

// steady_clock: 단조 증가
auto steady = std::chrono::steady_clock::now();

// high_resolution_clock: 고정밀
auto high = std::chrono::high_resolution_clock::now();
```Special features of each watch:

| clock | Characteristics | epoch | Usage Scenarios |
|------|------|-------|-------------|
| `system_clock` | Actual time, impact of system time changes | 1970-01-01 UTC | timestamp, file time |
| `steady_clock` | Monotonically increasing, independent of system time changes | Implementation dependent | Elapsed time, timeout |
| `high_resolution_clock` | highest resolution | Implementation dependent | Short section measurement |

Practice Recommendations:
- Requires actual time: `system_clock` (log, file modification time)
- Elapsed time measurement: `steady_clock` (timeout, benchmark)```cpp
// ✅ 로그 타임스탬프: system_clock
auto now = system_clock::now();
auto time_t = system_clock::to_time_t(now);
std::cout << "Log at: " << std::ctime(&time_t);

// ✅ 경과 시간 측정: steady_clock
auto start = steady_clock::now();
// ... 작업 ...
auto elapsed = steady_clock::now() - start;
```## Frequently occurring problems

### Problem 1: Clock change```cpp
// ❌ system_clock (시스템 시간 변경 영향)
auto start = std::chrono::system_clock::now();
// 시스템 시간 변경
auto end = std::chrono::system_clock::now();
// 음수 duration 가능

// ✅ steady_clock
auto start = std::chrono::steady_clock::now();
auto end = std::chrono::steady_clock::now();
// 항상 양수
```### Issue 2: Watch Compatibility```cpp
auto sys = std::chrono::system_clock::now();
auto steady = std::chrono::steady_clock::now();

// ❌ 다른 시계 비교
// auto diff = sys - steady;  // 에러

// 같은 시계 사용
```### Problem 3: Precision```cpp
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
    now.time_since_epoch()
);

// 밀리초 이하 정보 손실
```### Problem 4: Time zone```cpp
// system_clock은 UTC
auto now = std::chrono::system_clock::now();
auto tt = std::chrono::system_clock::to_time_t(now);

// 로컬 시간 변환
std::cout << std::ctime(&tt);  // 로컬 시간
```C++20 Time Zone Support:```cpp
#include <chrono>
#include <iostream>

using namespace std::chrono;

// UTC 시간
auto now = system_clock::now();

// 로컬 타임존
auto local = zoned_time{current_zone(), now};
std::cout << "Local: " << local << '\n';

// 특정 타임존
auto ny = zoned_time{"America/New_York", now};
auto tokyo = zoned_time{"Asia/Tokyo", now};

std::cout << "New York: " << ny << '\n';
std::cout << "Tokyo: " << tokyo << '\n';
```## Time operations```cpp
using namespace std::chrono;

auto now = system_clock::now();

// 더하기
auto future = now + hours(1);

// 빼기
auto past = now - minutes(30);

// 차이
auto diff = future - past;
```Operation rules:

| operations | Result Type | Example |
|------|----------|------|
| `time_point + duration` | `time_point` | `now + 1h` |
| `time_point - duration` | `time_point` | `now - 30min` |
| `time_point - time_point` | `duration` | `end - start` |
| `time_point == time_point` | `bool` | `t1 == t2` |
| `time_point < time_point` | `bool` | `t1 < t2` |

Practical example:```cpp
// 타임아웃 체크
auto deadline = steady_clock::now() + 5s;
while (steady_clock::now() < deadline) {
    if (try_operation()) break;
    std::this_thread::sleep_for(100ms);
}

// 파일 나이 확인
auto file_time = fs::last_write_time("file.txt");
auto now = fs::file_time_type::clock::now();
auto age = now - file_time;
if (age > 24h) {
    std::cout << "파일이 24시간 이상 오래됨\n";
}
```## Practice pattern

### Pattern 1: Timeout check```cpp
class TimeoutChecker {
    steady_clock::time_point deadline_;
    
public:
    TimeoutChecker(milliseconds timeout) 
        : deadline_(steady_clock::now() + timeout) {}
    
    bool expired() const {
        return steady_clock::now() >= deadline_;
    }
    
    milliseconds remaining() const {
        auto now = steady_clock::now();
        if (now >= deadline_) return milliseconds::zero();
        return duration_cast<milliseconds>(deadline_ - now);
    }
};

// 사용
TimeoutChecker checker(5s);
while (!checker.expired()) {
    std::cout << "남은 시간: " << checker.remaining().count() << "ms\n";
    std::this_thread::sleep_for(1s);
}
```### Pattern 2: Periodic tasks```cpp
class PeriodicTask {
    steady_clock::time_point next_run_;
    milliseconds interval_;
    
public:
    PeriodicTask(milliseconds interval) 
        : next_run_(steady_clock::now()), interval_(interval) {}
    
    bool should_run() {
        auto now = steady_clock::now();
        if (now >= next_run_) {
            next_run_ = now + interval_;
            return true;
        }
        return false;
    }
};

// 사용
PeriodicTask task(1s);  // 1초마다
while (true) {
    if (task.should_run()) {
        std::cout << "작업 실행\n";
    }
    std::this_thread::sleep_for(100ms);
}
```### Pattern 3: Log Timestamp```cpp
std::string format_timestamp(system_clock::time_point tp) {
    auto time_t = system_clock::to_time_t(tp);
    auto ms = time_point_cast<milliseconds>(tp);
    auto ms_part = ms.time_since_epoch().count() % 1000;
    
    char buf[64];
    std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&time_t));
    
    return std::string(buf) + "." + std::to_string(ms_part);
}

// 사용
void log(const std::string& msg) {
    auto now = system_clock::now();
    std::cout << format_timestamp(now) << " " << msg << '\n';
}
```## time_point structure (template and semantics)

`std::chrono::time_point<Clock, Duration>` stores **the point in time based on the epoch of the corresponding `Clock` as `Duration`.

- `Clock`: Provides nested types such as `now()`, `time_point`, and `duration`. The `time_point` of different `Clock`s cannot be directly subtracted or compared.
- Duration: Usually `Clock::duration` or a suitable `std::chrono::duration<Rep, Period>`. Even for the same clock, `time_point<steady_clock, milliseconds>` and `time_point<steady_clock, nanoseconds>` are different types, so set them to `time_point_cast` if necessary.```cpp
using namespace std::chrono;

steady_clock::time_point t1 = steady_clock::now();
auto t2 = time_point_cast<milliseconds>(t1);  // 해상도만 바뀜, 시계 동일
```The default value `time_point{}` often points to the epoch, so it is safer to use `std::optional` or a separate flag when expressing “no value” in the API.

## Relationship with duration (advanced)

- `time_point` is the “point of time”, and `duration` is the “interval”.
- On the same clock: `time_point - time_point` → `duration`, `time_point ± duration` → `time_point`.
- epoch: `tp.time_since_epoch()` is the `duration` from the epoch of `Clock`. If `system_clock`, it is usually a tick based on 1970-01-01 UTC.

To deal with calendar dates (year·month·day), a conversion flow to calendar type such as C++20's `std::chrono::year_month_day` is required, and `time_point` alone does not express all leap second and time zone rules. I recommend looking at it along with the [Calendar & Timezone](/blog/cpp-calendar-timezone/) topic.

## Temporal Operations: Pitfalls and Recommendations

- Do not mix clocks: `system_clock::now() - steady_clock::now()` will not compile and is meaningless.
- `sleep_until` and clock: Use `steady_clock::time_point` to set the wake-up time so it will not be shaken by system time changes. If you only use `system_clock::now() + 5s`, it may behave differently than intended when the user changes the time.
- Overflow: Adding extremely large `duration`s can exceed implementation/domain limits, so it is safe to have a “maximum duration” rule.

## In Practice: Timestamps and Expiration Times

Time stamp (log·API): Usually, take `system_clock::now()`, change `time_since_epoch()` to milliseconds, etc. and put it in JSON·Protobuf. Unifying to UTC and applying the local time zone only when displaying will reduce confusion.```cpp
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
    now.time_since_epoch()).count();
// wire: int64_t ms since Unix epoch (UTC)
```Expiration time (token·cache): If the “real time” is important, store `expires_at` with `system_clock::time_point`. If you want to use only the duration regardless of device power saving or time changes, such as “5 minutes after registration”, set the standard as `steady_clock`, or if the domain allows, save only all based on UTC epoch.

## Serialization (Wire format)

For compatibility with other processes and languages, we recommend the following:

1. Integer since Unix epoch: Document units as one of nano/micro/millisecond. Example: `int64_t milliseconds_since_epoch`.
2. ISO 8601 string: Suitable for human reading or logging. `system_clock` → Serialize to `time_t`/`tm` or a C++20 formatter.
3. Specify clock type: The `time_point` of `steady_clock` is meaningless on other machines even if serialized. Do not use it for restarts or “expires” to be shared with other machines.
4. Deserialize: Beware of overflow and unit confusion (µs vs ms) when restoring integer → `duration` → `system_clock::time_point`.```cpp
std::chrono::system_clock::time_point tp{
    std::chrono::milliseconds{millis_from_wire}
};
```In binary protocols, both endianness and signed 64-bit range are considered sufficient.

## FAQ

### Q1: What is time_point?

A: A type that represents the elapsed time from the epoch of a specific clock. Represents a specific time point.

### Q2: Which watch should I use?

A: 
- system_clock: When actual time is required (log, file time)
- steady_clock: When measuring elapsed time (timeout, benchmark)

### Q3: How to convert to timestamp?

A: Use `system_clock::to_time_t()`.```cpp
auto now = system_clock::now();
auto time_t = system_clock::to_time_t(now);
std::cout << std::ctime(&time_t);
```### Q4: How do you calculate time?

A: You can use `+`, `-`, and comparison operators. `time_point + duration = time_point`, `time_point - time_point = duration`.

### Q5: What clock is used to measure performance?

A: `steady_clock` is recommended. Monotonically increasing is guaranteed, unaffected by system time changes.

### Q6: What is C++20 time zone support?

A: Time zone conversion is possible using `zoned_time` and `time_zone`.```cpp
auto now = system_clock::now();
auto ny = zoned_time{"America/New_York", now};
```### Q7: What is the difference between time_point and duration?

A: 
- time_point: A specific point in time (e.g. "2026-03-12 14:30:00")
- duration: time interval (e.g. "5 seconds")

### Q8: What is epoch?

A: The reference point of the clock. The epoch of `system_clock` is usually 1970-01-01 00:00:00 UTC.

### Q9: What are time_point learning resources?

A:
- "C++ Primer" by Lippman, Lajoie, Moo
- "Effective Modern C++" by Scott Meyers
- [cppreference.com - std::chrono::time_point](https://en.cppreference.com/w/cpp/chrono/time_point)

Related posts: [duration](/blog/cpp-duration/), [time conversion](/blog/cpp-time-conversion/), [chrono](/blog/cpp-chrono/), [stopwatch·benchmark](/blog/cpp-stopwatch-benchmark/).

One line summary: time_point represents a time point on a specific clock and can be used with duration to perform time operations.

---

## Good article to read together (internal link)

Here's another article related to this topic.

- [C++ duration | “Time interval” guide](/blog/cpp-duration/)
- [C++ time conversion | chrono duration_cast and clock conversion](/blog/cpp-time-conversion/)
- [C++ Chrono | "Time Library" Guide](/blog/cpp-chrono/)
- [C++ Stopwatch and Benchmark | Measuring execution time with chrono](/blog/cpp-stopwatch-benchmark/)

## Practical tips

These are tips that can be applied right away in practice.

### Debugging tips
- If you run into a problem, check the compiler warnings first.
- Reproduce the problem with a simple test case

### Performance Tips
- Don't optimize without profiling
- Set measurable indicators first

### Code review tips
- Check in advance for areas that are frequently pointed out in code reviews.
- Follow your team's coding conventions

---
## Practical checklist

This is what you need to check when applying this concept in practice.

### Before writing code
- [ ] Is this technique the best way to solve the current problem?
- [ ] Can team members understand and maintain this code?
- [ ] Does it meet the performance requirements?

### Writing code
- [ ] Have you resolved all compiler warnings?
- [ ] Have you considered edge cases?
- [ ] Is error handling appropriate?

### When reviewing code
- [ ] Is the intent of the code clear?
- [ ] Are there enough test cases?
- [ ] Is it documented?

Use this checklist to reduce mistakes and improve code quality.

---

## Keywords covered in this article (related search terms)

This article will be helpful if you search for C++, time_point, chrono, clock, C++11, etc.

---

## Related articles

- [C++ Chrono Complete Guide | ](/blog/cpp-chrono-guide/)
- [C++ Chrono Detailed Guide | ](/blog/cpp-chrono/)
- [C++ duration | ](/blog/cpp-duration/)
- [C++ ratio | ](/blog/cpp-ratio-guide/)
- [C++ steady_clock | ](/blog/cpp-steady-clock/)