英文:
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 <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)
{
}
}
答案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_point
s 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论