What is the difference between floor and duration_cast?

So in C ++ 11, the Chrono Library provides a duration_cast :

The calculations are performed in the widest possible and converted form, as if static_cast, to the type of the result only at the end

And C ++ 17 floor :

Returns the largest duration t represented in ToDuration that is less than or equal to d

So, for all x result of these two calls will be:

  • chrono::duration_cast<chrono::seconds>(x)
  • chrono::floor<chrono::seconds>(x)
+7
c ++ c ++ 11 floor chrono c ++ 17
source share
1 answer

As far as I can tell, the same as the difference between static_cast and std::floor : the cons are rounded down, not truncated to zero.

 #include <iostream> #include <chrono> using namespace std::chrono_literals; int main() { std::cout << "duration_cast:" << std::endl; std::cout << "1.4s: " << std::chrono::duration_cast<std::chrono::seconds>(1400ms).count() << std::endl; std::cout << "1.5s: " << std::chrono::duration_cast<std::chrono::seconds>(1500ms).count() << std::endl; std::cout << "1.6s: " << std::chrono::duration_cast<std::chrono::seconds>(1600ms).count() << std::endl; std::cout << "-1.4s: " << std::chrono::duration_cast<std::chrono::seconds>(-1400ms).count() << std::endl; std::cout << "-1.5s: " << std::chrono::duration_cast<std::chrono::seconds>(-1500ms).count() << std::endl; std::cout << "-1.6s: " << std::chrono::duration_cast<std::chrono::seconds>(-1600ms).count() << std::endl; std::cout << "floor:" << std::endl; std::cout << "1.4s: " << std::chrono::floor<std::chrono::seconds>(1400ms).count() << std::endl; std::cout << "1.5s: " << std::chrono::floor<std::chrono::seconds>(1500ms).count() << std::endl; std::cout << "1.6s: " << std::chrono::floor<std::chrono::seconds>(1600ms).count() << std::endl; std::cout << "-1.4s: " << std::chrono::floor<std::chrono::seconds>(-1400ms).count() << std::endl; std::cout << "-1.5s: " << std::chrono::floor<std::chrono::seconds>(-1500ms).count() << std::endl; std::cout << "-1.6s: " << std::chrono::floor<std::chrono::seconds>(-1600ms).count() << std::endl; return 0; } 

.

 duration_cast: 1.4s: 1 1.5s: 1 1.6s: 1 -1.4s: -1 -1.5s: -1 -1.6s: -1 floor: 1.4s: 1 1.5s: 1 1.6s: 1 -1.4s: -2 -1.5s: -2 -1.6s: -2 

https://wandbox.org/permlink/SsmpRz6RkvbL6Sru

+10
source share

All Articles