Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a double from boost::chrono::steady_clock::now()

Tags:

c++

boost

How would I get a double value from boost::chrono::steady_clock::now()? I don't believe there is a .count() parameter for this.

Why do I need this? I have a method that cannot parse the boost return.

like image 369
bge0 Avatar asked Dec 01 '22 19:12

bge0


2 Answers

  • boost::chrono::steady_clock::now() returns a boost::chrono::time_point.
  • boost::chrono::time_point has a time_since_epoch method which returns a boost::chrono::duration.
  • boost::chrono::duration has a count method that gives you a scalar.

When we put it all together, it boils down to:

auto now = boost::chrono::steady_clock::now().time_since_epoch();
auto timeSinceEpoch = boost::chrono::duration_cast<boost::chrono::milliseconds>(now).count();

Granted that's not a double but close enough: you can change the duration_cast to get whatever precision you need and/or divide the timeSinceEpoch to your liking so that your double fits your requirements. For example:

// Days since epoch, with millisecond (see duration_cast above) precision
double daysSinceEpoch = double(timeSinceEpoch) / (24. * 3600. * 1000.);
like image 198
syam Avatar answered Dec 13 '22 18:12

syam


you can specify double inside duration:

auto some_time = std::chrono::high_resolution_clock::now();
double duration = std::chrono::duration_cast<std::chrono::duration<double>>(some_time).count();
like image 28
kirill_igum Avatar answered Dec 13 '22 18:12

kirill_igum