C++如何检查两个毫秒值的差异是否为正?

标签 c++ c++-chrono

我需要引入至少 2 秒的延迟。为此,我这样做了:

typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds Milliseconds;
Clock::time_point t0 = Clock::now();

// DO A LOTS OF THINGS HERE.....

Clock::time_point t1 = Clock::now();
Milliseconds delayTime = Milliseconds(2000) - 
     std::chrono::duration_cast<Milliseconds>(t1 - t0); 

// Check if time left from initial 2 seconds wait the difference
if (delayTime > Milliseconds(0))
{
    std::this_thread::sleep_for(delayTime);
}

如果还有时间,我检查正确了吗?

最佳答案

除非你真的需要确保在 2 秒已经过去时根本不调用 sleep ,否则计算 sleep 何时结束似乎要容易得多,然后调用 sleep_until,传递那个时间。

auto t1 = Clock::now() + 2s; // beware: requires C++14

// do lots of things here

std::this_thread::sleep_until(t1);

如果 2 秒已经过去,sleep_until(至少可能)立即返回。如果还没有过去,线程会休眠到指定的时间。

关于C++如何检查两个毫秒值的差异是否为正?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665143/

相关文章:

c++ - C 删除链表中的节点

c++ - 可以在声明它们的命名空间之外定义类成员吗?

c++ - CodeBlocks:如何动态链接 libstdc++?

c++ - 指定不同访问器中静态局部变量的构造/销毁顺序

c++ - std::chrono::steady_clock::now 应该是 noexcept 吗?

c++ - operator= 在两个 std::chrono::time_point 之间导致错误

c++ - 如何初始化静态类的疙瘩成语的d(指针)?

c++ - 使用 chrono 存储毫秒的可移植方式

c++ - 如何将持续时间添加到time_point?

c++ - now() 调用标准计时时钟的性能保证?