Understanding system_clock in C++: Differences Across Compilers

Understanding system_clock in C++ <chrono>: Differences Across Compilers

Fracis
1 min readJun 7, 2024

When dealing with time in modern C++ programming, the <chrono> library provides a set of high-precision time handling tools. A widely used clock type within this library is system_clock. However, developers may encounter subtle differences when compiling the same code with different compilers, particularly in terms of the default time unit for system_clock. This article explores this issue and offers solutions to handle it effectively.

Default Time Units in Different Compilers

GCC (g++-13)

In GCC, the default time unit for system_clock is nanoseconds (std::chrono::nanoseconds). This is defined as follows:

struct system_clock
{
typedef chrono::nanoseconds duration;
};

Clang

In Clang, the default time unit for system_clock is microseconds (std::chrono::microseconds). It is defined as:

class _LIBCPP_TYPE_VIS system_clock
{
public:
typedef microseconds duration;
};

This discrepancy means that when compiling the same code with different compilers, the precision and behavior of time calculations can vary.

But steady_clock is indeed consistent.

g++:

struct steady_clock
{
typedef chrono::nanoseconds duration;
}

clang:

class _LIBCPP_TYPE_VIS steady_clock
{
public:
typedef nanoseconds duration;
}
Photo by Jakub Dziubak on Unsplash

--

--

Fracis

Stories About C Plus Plus,Arrow and DuckDB contributor