What's the Difference Between floor and duration_cast?

纵然是瞬间 提交于 2019-12-30 08:15:13

问题


So in c++11 the Chrono Library provides, duration_cast:

Computations are done in the widest type available and converted, as if by static_cast, to the result type only when finished

And c++17's floor:

Returns the greatest duration t representable in ToDuration that is less or equal to d

So for all x will the result of these 2 calls be equal:

  1. chrono::duration_cast<chrono::seconds>(x)
  2. chrono::floor<chrono::seconds>(x)

回答1:


As far as I can tell, same as the difference between static_cast and std::floor: Negatives are rounded down instead of truncated toward 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



来源:https://stackoverflow.com/questions/48468068/whats-the-difference-between-floor-and-duration-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!