More general implementation.
template<typename Duration> void to_timeval(Duration&& d, struct timeval & tv) { std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d); tv.tv_sec = sec.count(); tv.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>(d - sec).count(); }
UPDATE:
Separate methods like to_timeval() are not very convenient. Where is the overload? We only have the hard code timeval in the function name to_timeval() . This is not C ++. I want to pass the struct timeval to, for example, std::chrono::duration_cast() and get my chrono result and vice versa.
So, we can expand std::chrono::duration_cast (of course, at our own peril and risk). Enjoy it.
namespace std { namespace chrono { namespace detail { template<typename From, typename To> struct posix_duration_cast;
This is just an example. Alternatively, we can implement our own duration_cast() and in some cases forward it to std::chrono::duration_cast() .
And we remember about struct timespec .
source share