Reputation: 85
I'm using Chrono to standardize the usage of timestamps in an application.
Given a timestamp, I would create a timepoint. I'd then convert it to time_t to pass it as a parameter.
std::chrono::system_clock::to_time_t (timePoint)
Should I be passing a timepoint instead? What seems to be best practice?
void func(time_t time)
or
void func(std::chrono::time_point timePoint)
Upvotes: 3
Views: 1349
Reputation: 218700
My advice is that unless you have to drop down to the C API (e.g. time_t
) for compatibility with some other code that uses it, just stay in <chrono>
(e.g. std::chrono::system_clock::time_point
). It has better precision, and is a unique type with the semantics "time point" instead of just an integral type.
That is, my vote is:
void func(std::chrono::system_clock::time_point timePoint);
C++20 will bring many facilities to make it easier to work with the <chrono>
types, and those facilities are prototyped in a free open source library:
https://github.com/HowardHinnant/date
Note I slightly altered your suggestion. std::chrono::time_point
is a class template, not a type:
template<class Clock, class Duration = typename Clock::duration>
class time_point;
I chose system_clock
as that is the clock that is analogous to the C type time_t
. It counts time since since 1970-01-01 00:00:00 UTC, except at a higher precision than time_t
typically does.
And system_clock::time_point
is a type alias for time_point<system_clock>
(you could use either).
For a video tutorial on <chrono>
, see: https://www.youtube.com/watch?v=P32hvk8b13M
Upvotes: 2