floor和duration_cast之间有什么区别?

时间:2018-01-26 19:14:08

标签: c++ c++11 chrono floor c++17

因此,在Chrono图书馆的中提供了duration_cast

  

计算是在最广泛的类型中完成的,并且只有在完成时才会转换为结果类型,就好像通过static_cast一样转换

floor

  

返回ToDuration中可表示的最大持续时间t,该持续时间小于或等于d

因此,对于所有x,这两个调用的结果将是相等的:

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

1 个答案:

答案 0 :(得分:11)

据我所知,与static_caststd::floor之间的差异相同:负数被舍入而不是截断为零。

#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