You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确比较时间点t与两个时间点的差值elapsed?

问题解答

核心概念澄清

首先明确:elapsed 不是时间点,它是两个time_point相减得到的时间间隔(duration),代表从begin到cur流逝了多久;而TimePoint是某个时钟下的具体时刻(比如从时钟纪元开始过了多久的那个点),这是两种完全不同的类型,不能直接比较——你代码里的if (elapsed <= t)会编译报错,因为类型不匹配。

正确的比较方式

要验证流逝时间是否≤100ms,只需要把阈值也定义成duration类型,直接和elapsed比较即可:

#include <chrono>
#include <thread>

using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;

int main() 
{
    TimePoint begin = Clock::now();

    std::chrono::seconds delay(2);
    std::this_thread::sleep_for(delay);
    
    auto cur = Clock::now();
    auto elapsed = cur - begin;

    // 把阈值定义为duration类型,而非time_point
    std::chrono::milliseconds threshold(100);

    // 直接比较两个时间间隔
    if (elapsed <= threshold)
    {
        // 流逝时间≤100ms时执行的逻辑
    }
}

另一种实现思路

如果你习惯用时间点逻辑,也可以计算begin加上100ms后的截止时刻,再判断当前时间是否未超过这个时刻,效果完全一致:

#include <chrono>
#include <thread>

using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;

int main() 
{
    TimePoint begin = Clock::now();
    // 计算允许的最晚时间点:起始时刻 + 100ms
    TimePoint deadline = begin + std::chrono::milliseconds(100);

    std::chrono::seconds delay(2);
    std::this_thread::sleep_for(delay);
    
    auto cur = Clock::now();

    // 比较当前时间是否在截止时间范围内
    if (cur <= deadline)
    {
        // 流逝时间≤100ms时执行的逻辑
    }
}

两种方式都能实现需求,选哪种看你的代码逻辑习惯。

内容的提问来源于stack exchange,提问作者xyf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:25:11