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?
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.
来源:https://stackoverflow.com/questions/21050994/stdchrono-default-duration-for-time-since-epoch