std::chrono default duration for time_since_epoch

a 夏天 提交于 2019-12-08 01:28:37

问题


If I have the following clock and use it to get a count of ticks since the clock's epoch, what does this count actually represent.

std::chrono::high_resolution_clock::now().time_since_epoch().count();

For instance I just ran this and got 1389375799048790227. What does this number mean? Is it nanoseconds, microseconds, etc?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/21050994/stdchrono-default-duration-for-time-since-epoch

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