比较一个时间点与时间点的差异。

huangapple go评论82阅读模式
英文:

Comparing a time point with a difference of time points

问题

如何比较时间点 t 和两个时间点之间的差值 elapsed?换句话说,我正在验证迄今为止经过的时间是否小于或等于给定的时间点,即 100 毫秒。

elapsed 不应该是一个时间点本身吗?与 t 比较应该没有问题吧?

#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;

    TimePoint t = TimePoint(std::chrono::milliseconds(100));

    if (elapsed <= t)
    {
        
    }
}
英文:

How does one go about comparing the time point t with elapsed which is difference between two time points? In other words, I am verifying whether time elapsed so far is <= the given time point i.e 100ms.

Shouldn't elapsed be a time point itself and comparing with t be no issue?

#include &lt;chrono&gt;
#include &lt;thread&gt;

using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point&lt;Clock&gt;;

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;

    TimePoint t = TimePoint(std::chrono::milliseconds(100));

    if (elapsed &lt;= t)
    {
        
    }
}

答案1

得分: 1

两个time_point之间的差异不是一个std::chrono::time_point,而是一个表示时间间隔的std::chrono::duration

因此,您需要将这一行代码修改为:

std::chrono::duration t = std::chrono::milliseconds(100);

或者简单地使用auto,编译器将会推断出这个类型:

auto t = std::chrono::milliseconds(100);
英文:

The difference between 2 time_points is not a std::chrono::time_point but rather a std::chrono::duration, which represents a time interval.

Therefore you need to change this line:

TimePoint t = TimePoint(std::chrono::milliseconds(100));

Into:

std::chrono::duration t = std::chrono::milliseconds(100);

Or simply use auto so that the compiler will infer this type:

auto t = std::chrono::milliseconds(100);

huangapple
  • 本文由 发表于 2023年5月21日 12:05:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定