【问题标题】:How can we make a loop with chronicle statement in C++?我们如何在 C++ 中使用 Chronicle 语句创建循环?
【发布时间】:2016-05-15 16:33:09
【问题描述】:

我想知道如何创建一个循环(例如 while 循环),其中 while 循环内的语句是基于时间的。

为了更清楚,例如,我想创建一个 while 循环,我将每 10 秒输入一次。

伪代码应该是这样的:

while (10 seconds have passed)
{
    //do Something
}

那么,如何才能使上面的伪代码成为真实的呢? (我希望已经清楚了)

【问题讨论】:

  • 检查您可以从std::chronostd::thread 获得什么。
  • 这个while循环是否每10秒执行一次?

标签: c++


【解决方案1】:

我通常使用这样的东西:

// for an easier life
using clock = std::chrono::steady_clock;

// set the baseline time
auto timeout = clock::now();

for(;;)
{
    // (re)set timer
    timeout += std::chrono::seconds(10);

    // sleep until time has elapsed
    std::this_thread::sleep_until(timeout);

    // do something useful (like print the time)
    auto timer = std::time(0);
    std::cout << "loop: " << std::ctime(&timer) << '\n';
}

通过使用std::this_thread::sleep_until(),循环在等待10 秒过去时不会消耗CPU 时间。

这可以包含在一个整洁的小类中,如下所示:

class wait_timer
{
    using clock = std::chrono::steady_clock;

    clock::duration time_to_wait;
    clock::time_point timeout = clock::now();

public:
    wait_timer(std::chrono::milliseconds ms)
    : time_to_wait(ms), timeout(clock::now()) {}

    void wait()
    {
        timeout += time_to_wait; // (re)set timer
        std::this_thread::sleep_until(timeout);
    }
};

int main()
{
    // create it outside the loop so it doesn't
    // loose track of time every iteration
    wait_timer wt(std::chrono::seconds(2));

    for(;;)
    {
        wt.wait();

        // do something useful (like print the time)
        auto timer = std::time(0);
        std::cout << "loop: " << std::ctime(&timer) << '\n';
    }
}

【讨论】:

    【解决方案2】:

    您可以使用&lt;time.h&gt; 头文件,并使用内部时钟来测量是否已经过了 10 秒

    clock_t t;
    
    while (1) {    // This loop runs exactly once every 10 seconds
        t = clock();    // Reset clock
    
        // Do something in this loop
    
        while ((double)(clock()-t)/CLOCKS_PER_SEC < 10);    // Wait if 10 seconds havent passed
    
    }
    

    如果您在 while 循环中的计算时间超过 10 秒,这将失败

    【讨论】:

      【解决方案3】:

      你可以使用std::this_thread::sleep_for:

      #include <thread>
      #include <chrono>
      using namespace std;
      using namespace std::chrono_literals;
      
      int main()
      {
          while (1) {
              // some code
      
              this_thread::sleep_for(10s);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-12-27
        • 2015-01-01
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-25
        • 1970-01-01
        相关资源
        最近更新 更多