c++ - 检查 std::chrono 持续时间小于 0 的惯用方法

标签 c++ c++20 chrono

我知道我可以做到这一点

if (timeLeft.count() < 0)
但我想知道什么是最好的方法,因为我也可以这样做:
if (timeLeft<std::chrono::seconds(0)) // or milliseconds or nanonseconds...
注意:我假设两个检查是相同的,但我不是计时专家。
编辑:完整示例:
#include<chrono>
int main(){
    const std::chrono::nanoseconds timeLeft(-5);
    if(timeLeft<std::chrono::seconds(0)){
        return 47;
    }
}
编辑 2:std::chrono::seconds(0) 的潜在问题是新手程序员可能会认为它涉及舍入,尽管它没有。

最佳答案

表达这一点的方法之一是使用 std::chrono::duration 文字( https://en.cppreference.com/w/cpp/chrono/duration )。它简短而干净:

#include<chrono>

int main(){
    using namespace std::chrono_literals;
    
    const auto timeLeft = -5ns;
    if(timeLeft<0s){
        return 47;
    }
}

关于c++ - 检查 std::chrono 持续时间小于 0 的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64206448/

相关文章:

c++ - 重载 [] 和 , c++11

c++ - 使用 std::ofstream 写入文件比使用 std::cout 慢,然后将该输出重定向到日志文件

c++ - chrono::month 和 chrono::months 有什么区别

c++ - std::chrono::system_clock 使用什么精度?

c++ - 解析模板和 const volatile 类型

c++ - 为什么 std::rel_ops::operators 在 C++20 中被弃用?

c++ - 为什么我不能在 c++20 中的 istream_view 之后使用 take()

c++ - 精确的时间测量

c++ - 如何在不使用 time_t 的情况下将 std::chrono::time_point 转换为 std::tm?

c++ - Socket connect() 总是成功(TCP over ActiveSync)