6

标题说明了一切。

我必须实现一个接收 std::chrono::system_clock::duration 值的函数,并且需要将其转换为 timeval sruct,以便我可以将其传递给某个系统函数。

4

2 回答 2

9

更一般的实现。

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();
}

更新:

像这样的单独方法to_timeval()不太方便。哪里有超载的力量?我们刚刚将 type 硬编码timeval为 function 的名称to_timeval()。这不是 C++ 方式。struct timeval例如,我想传递std::chrono::duration_cast()给我的chrono结果,反之亦然。

因此,我们可以扩展std::chrono::duration_cast(当然,风险自负)。享受。

namespace std {
namespace chrono {
namespace detail {

template<typename From, typename To>
struct posix_duration_cast;

// chrono -> timeval caster
template<typename Rep, typename Period>
struct posix_duration_cast< std::chrono::duration<Rep, Period>, struct timeval > {

    static struct timeval cast(std::chrono::duration<Rep, Period> const& 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();

        return std::move(tv);
    }

};

// timeval -> chrono caster
template<typename Rep, typename Period>
struct posix_duration_cast< struct timeval, std::chrono::duration<Rep, Period> > {

    static std::chrono::duration<Rep, Period> cast(struct timeval const & tv) {
        return std::chrono::duration_cast< std::chrono::duration<Rep, Period> >(
                    std::chrono::seconds(tv.tv_sec) + std::chrono::microseconds(tv.tv_usec)
                    );
    }

};

}

// chrono -> timeval    
template<typename T, typename Rep, typename Period>
auto duration_cast(std::chrono::duration<Rep, Period> const& d)
-> std::enable_if_t< std::is_same<T, struct timeval>::value, struct timeval >
{
    return detail::posix_duration_cast< std::chrono::duration<Rep, Period>, timeval >::cast(d);
}

// timeval -> chrono
template<typename Duration>
Duration duration_cast(struct timeval const& tv) {
    return detail::posix_duration_cast< struct timeval, Duration >::cast(tv);
}

} // chrono
} // std

这只是一个例子。作为替代方案,我们可以实现自己的duration_cast(),并在某些情况下将其转发到std::chrono::duration_cast().

我们记得大约struct timespec

于 2015-09-24T14:18:45.290 回答
6

Let d be the input duration value and tv the output timeval structure filled by the convert function. Note: the function sets the timeval to 0 if the duration is negative.

void convert( const std::chrono::system_clock::duration &d, timeval &tv )
{
  chrono::microseconds usec = chrono::duration_cast<chrono::microseconds>(d);
  if( usec <= chrono::microseconds(0) )
    tv.tv_sec = tv.tv_usec = 0;
  else
  {
    tv.tv_sec = usec.count()/1000000;
    tv.tv_usec = usec.count()%1000000;
  }
}
于 2013-07-02T10:22:58.547 回答