std::chrono default duration for time_since_epoch

馋奶兔 提交于 2019-12-06 11:17:30

The type of the duration is std::chrono::high_resolution_clock::duration. You can inspect a duration's tick period with: std::chrono::high_resolution_clock::duration::period::num and std::chrono::high_resolution_clock::duration::period::den. This is the numerator and denominator of a fraction representing the amount of seconds per tick (e.g. 1/1000000000 for nanoseconds).

The epoch is unspecified, but for you is 1389375799048790227 ticks from when you got that result.

you can always cast it to your desired time unit using duration_cast

using namespace std::chrono;
auto time = duration_cast<seconds>(high_resolution_clock::now().time_since_epoch());

now time.count() will return number of seconds.

You can use the trick from Item 4 of Scott Meyers' Effective Modern C++ to make the compiler reveal the type in an error message, like so:

#include <chrono>

template < typename T >
struct TypeDiscloser;

int main() {
    auto epoch_time = std::chrono::high_resolution_clock::now().time_since_epoch();
    TypeDiscloser< decltype( epoch_time ) > dummyVar;
}

On ideone, this gives the following compiler error:

prog.cpp: In function 'int main()':
prog.cpp:9:42: error: aggregate 'TypeDiscloser<std::chrono::duration<long long int, std::ratio<1ll, 1000000000ll> > > dummyVar' has incomplete type and cannot be defined
  TypeDiscloser< decltype( epoch_time ) > dummyVar;
                                          ^

From the compiler error, the type is:

std::chrono::duration<long long int, std::ratio<1ll, 1000000000ll> >

So on whatever platform ideone is running, std::chrono::time_point::time_since_epoch() returns a std::chrono::duration with a tick period of 1/1000000000 seconds, or 1 nanosecond. So calling count() on that duration returns nanoseconds.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!