Time in C/C++: <ctime> & std::chrono
Published: April 5, 2026 | Category: Programming Time
Handling time in C and C++ involves navigating a history that spans from the earliest days of Unix to modern, type-safe template libraries. Depending on your needs for performance vs. safety, you might interact with the legacy C header or the modern C++20 extensions.
The Legacy C Approach: <ctime> (time.h)
Derived from original C, <ctime> uses simple types like time_t (usually a 64-bit integer representing seconds since the Unix Epoch) and struct tm for calendar representations.
#include <ctime>
time_t now = time(0);
struct tm* local = localtime(&now);
While simple, this approach is fraught with danger: it's not thread-safe (due to static buffers in localtime) and lacks sub-second precision.
The Modern C++ Approach: std::chrono
Introduced in C++11 and significantly expanded in C++20, <chrono> provides a type-safe, nanosecond-precise library. It separates the concepts of **clocks**, **time points**, and **durations**.
- system_clock: Wall clock time from the system.
- steady_clock: A monotonic clock that never goes backwards (crucial for measuring elapsed time).
- high_resolution_clock: The clock with the smallest tick period available.
C++20: Calendars and Timezones
C++20 finally brought high-level calendar and timezone support to the language. Developers can now perform arithmetic on years, months, and days natively, and even convert between timezones using the IANA database.
using namespace std::chrono;
auto today = year_month_day{ floor<days>(system_clock::now()) };
auto future = today + months{1};
Conclusion
C/C++ time handling has evolved from "seconds since 1970" to a sophisticated, type-safe system that can represent anything from geological eras to the vibration of atoms. For modern systems programming, std::chrono is the essential choice for both safety and performance.