floor 和 duration_cast 有什么区别?

What's the Difference Between floor and duration_cast?

所以 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

's floor

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

那么对于所有 x 这两个调用的结果是否相等:

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

据我所知,与 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