Reputation: 21
is there any significant difference between the chrono::system_clock::now()
and time(0)
functions, and their return value?
When should I use chrono::system_clock::now()
instead of time(0)
, and vice versa ?
Upvotes: 2
Views: 1699
Reputation: 218700
system_clock::now()
vs time(0)
system_clock::now()
and time(0)
measure the same thing: Unix Time. This is unspecified by time(0)
, but true in practice. It is also unspecified by system_clock::now()
in C++11/14/17, but true in practice. In C++20 it is specified by system_clock::now()
.
The precision (seconds, microseconds, whatever) reported by system_clock::now()
and time(0)
is unspecified. For system_clock
, the precision can be discovered by your application, either at compile time or run time. For time(0)
, the precision must be read by a human from the documentation. The typical precision for time(0)
is seconds. For LLVM on Apple OS's, the precision of sytem_clock::now()
is microseconds. On gcc/Linux, nanoseconds. And on Windows 1/10 of a microsecond. Because of the design of <chrono>
it is easy to write portable code that does not change with the underlying precision.
The range of time(0)
is unspecified, and on 32 bit machines typically about +/-68 years centered on 1970 (2038 is coming up fast...). On 64 bit machines the range of time(0)
is +/-292 billion years. The range of system_clock::now()
is discoverable at compile-time or run-time and is never less than +/-292 years (centered on 1970). The finer the precision, the smaller the range.
The return type of time(0)
is typically a signed integral type, which runs the risk of being confused with all of the other integral types in your application (no type safety). The return type of system_clock::now()
is a class type that has the semantics of a time point. It can not be confused with integral or floating point types. It is a distinct type from a time duration. Misuses of this time point in illogical ways are caught at compile time (strong type safety).
time(0)
interoperates with the rest of the date/time library in <time.h>
.
sytem_clock::now()
interoperates with the rest of the date/time library in <chrono>
. This includes conversions to and from time_t
returned by time(0)
. In C++11/14/17, calendrical and time zone functionality does not exist, but can be added on by free, open-source libraries.1 In C++20, full calendrical and time zone support exists within <chrono>
.
1 E.g.: Howard Hinnant's date/time library.
Upvotes: 5