I want to be able to get nanosecond accuracy with the chrono library but I can't figure out how to convert std::chrono::high_resolution_clock::now()
into long int
. I tried this:
#include <chrono>
#include <iostream>
using namespace std;
int main() {
typedef std::chrono::high_resolution_clock Clock;
long int val = Clock::now();
cout << val << endl;
cin.ignore();
return 0;
}
But this gave me the error: error C2440: 'initializing' : cannot convert from 'std::chrono::system_clock::time_point' to 'long'
How can I convert it to a 64 bit int? If I can't then I don't see how chrono is useful.
class Duration = typename Clock::duration. > class time_point; (since C++11) Class template std::chrono::time_point represents a point in time. It is implemented as if it stores a value of type Duration indicating the time interval from the start of the Clock 's epoch.
constexpr ToDuration duration_cast(const std::chrono::duration<Rep,Period>& d); (since C++11) Converts a std::chrono::duration to a duration of different type ToDuration . The function does not participate in overload resolution unless ToDuration is a specialization of std::chrono::duration.
A steady_clock is a monotonic clock, which means that the time it reports only moves forward.
The following works with GCC 4.8 on Linux:
using namespace std::chrono;
auto now = high_resolution_clock::now();
auto nanos = duration_cast<nanoseconds>(now.time_since_epoch()).count();
std::cout << nanos << '\n';
First, convert the time point returned by now()
into the duration since a known timepoint. This can either be the clock's epoch:
auto since_epoch = Clock::now().time_since_epoch();
or some timepoint that you've chosen:
auto since_epoch = Clock::now() - my_epoch;
Then you can get the number of nanoseconds either by converting and extracting the count:
auto nanos = duration_cast<nanoseconds>(since_epoch).count();
or by dividing by whatever granularity you want:
auto nanos = since_epoch / nanoseconds(1);
As noted in the comments, only do this last conversion (which leaves the Chrono library's type system, losing valuable information about what the number means) if you really need a scalar quantity; perhaps because you're interacting with an API that doesn't use the standard types. For your own calcuations, the types should allow you to perform any meaningful arithmetic that you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With