Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does duration_cast round

Tags:

c++

c++11

chrono

If I convert to a coarser unit of time (say std::chrono::minutes to std::chrono::hours) how will duration_cast round? For example, what value will std::chrono::minutes(91) become if converted to std::chrono::hours? 2h, 1h?

like image 273
RichardBruce Avatar asked Mar 21 '16 02:03

RichardBruce


People also ask

What is Duration_cast?

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.

How does STD Chrono work?

Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational fraction representing the time in seconds from one tick to the next. The only data stored in a duration is a tick count of type Rep .


1 Answers

duration_cast always rounds towards zero. I.e. positive values round down and negative values round up.

For other rounding options see:

http://howardhinnant.github.io/duration_io/chrono_util.html

floor, ceil, and round are currently in the draft C++ 1z (hopefully C++17) draft working paper. In the meantime feel free to use the code at chrono_util.html, and please let me know if you have any problems with it.


C++ 17 update

  • std::chrono::floor
  • std::chrono::ceil
  • std::chrono::round

std::chrono::floor<std::chrono::seconds>(1400ms)  ==  1s
std::chrono::floor<std::chrono::seconds>(1500ms)  ==  1s
std::chrono::floor<std::chrono::seconds>(1600ms)  ==  1s
std::chrono::floor<std::chrono::seconds>(-1400ms) == -2s
std::chrono::floor<std::chrono::seconds>(-1500ms) == -2s
std::chrono::floor<std::chrono::seconds>(-1600ms) == -2s
like image 189
Howard Hinnant Avatar answered Sep 18 '22 20:09

Howard Hinnant