【问题标题】:How to make an if statement based on how much time passed?如何根据经过的时间做出 if 语句?
【发布时间】:2018-03-10 02:19:53
【问题描述】:

我正在寻找一种添加if 语句的方法,如下所示,只是不确定如何去做。

if(120 seconds have passed)
{
    // do stuff
}

alt 将是(假设 x 是每次检查之间经过的时间)

do
{
    // do stuff
    x = 0;
}while(x=120)

所以它会不断循环。 谁能告诉我一个解决方案?

【问题讨论】:

  • 您是否查看过如何检查已经过去了多少时间,或者根本没有搜索过这个问题?我怀疑这个问题已经回答了几十次了。
  • 是的,但我不明白,有些答案是用 Chrono 的,有些是用 c++ 时间库的,我不明白如何使用它,所以我需要自己问这个@致癌
  • 您应该缩小这个问题的范围,因为上述问题在其他地方已经有了答案。如果您在使用 Chrono 时需要帮助,请展示您使用它的尝试,并具体说明您不了解的地方。
  • 这就是问题所在,很多答案都没有回答我的问题,我还不知道如何使用 Chrono 但是我可以将其缩小到这个范围;
  • @Jungha 1. 您可能需要检查 seconds_since_start 是否大于 120 不等于 (==) 到 120。如果您的程序在 119 秒处冻结几秒钟,它可能会跳过 120 秒并永远运行。 2. 你可以,是的。该变量只是一个双精度值。

标签: c++ time


【解决方案1】:

您可以使用Boost.DateTime 来完成这项工作。

以下是描述每个步骤的示例:

const boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
// Do stuff
const boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time();
const boost::posix_time::time_duration duration = end - start;
const boost::posix_time::time_duration remaining = boost::posix_time::seconds(120) - duration;
boost::this_thread::sleep(remaining);

可以这样简化:

const boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
// Do stuff
boost::this_thread::sleep(boost::posix_time::seconds(120) - boost::posix_time::microsec_clock::local_time() + start);

或者这样简化:

const boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time() + boost::posix_time::seconds(120);
// Do stuff
boost::this_thread::sleep(end - boost::posix_time::microsec_clock::local_time());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多