【问题标题】:How to execute a while-loop for exactly 60 seconds in C++?如何在 C++ 中执行 60 秒的 while 循环?
【发布时间】:2017-08-01 16:20:45
【问题描述】:

有谁知道我怎样才能让这个循环运行 60 秒然后停止?这是我的代码:

#include<iostream.h>
#include<conio.h>
int main()
{
    clrscr();
    int a=1;
    int b;
    cout<<"3.";
    b=a*10%7;
    while(b!=0)
    {
        cout<<a/7;
        a=b*10;
        b=a%7;
    }
    getch();
    return 0;
}

【问题讨论】:

  • 你想达到什么目的?延迟?
  • 创建一个startTime 变量并在while 循环的每次迭代中检查它。如果startTime过去超过60秒,break
  • @Xirema 看来 TurboC++,给定 iostream.h 和 conio.h
  • 你不能“精确地”运行 60 秒。检查当前时间可以给你“至少 60 秒”。您需要多少精度?秒、毫秒、微秒?..
  • 您没有使用 C++。您正在使用一种更古老的语言,现在完全过时且不受支持,大约在 20 年前它很流行时称为 C++。我们现在称为 C++ 的语言与您使用的语言非常不同。更多信息见here(警告:无耻插件)。

标签: c++ while-loop


【解决方案1】:

使用&lt;chrono&gt; 库。

#include<iostream>
#include<conio.h>
#include<chrono>

int main()
{
    clrscr();
    int a=1;
    int b;
    std::cout<<"3."; //Don't use 'using namespace std;'...
    b=a*10%7;
    std::chrono::steady_clock::timepoint start = std::chrono::steady_clock::now();
    while(b!=0)
    {
        std::cout<<a/7;
        a=b*10;
        b=a%7;
        if(std::chrono::steady_clock::now() - start > std::chrono::seconds(60)) 
            break;
    }
    getch();
    return 0;
}

【讨论】:

  • 您认为 iostream.h 的用户会喜欢这个答案吗?
  • 虽然如果他的标准库有一个名为&lt;iostream.h&gt;的头文件,我怀疑它有&lt;chrono&gt;。 (当然,并不是说这个答案有什么问题,因为它会对其他用户有用)
【解决方案2】:

在开始循环之前获取时间。增加 60 秒。每次通过循环获取时间并将其与您的目标时间进行比较。已经60秒了吗?如果是这样,请停止。

查看 http://en.cppreference.com/w/cpp/header/chrono 以获取 C++ 库头文件。

【讨论】:

    【解决方案3】:

    试试这个:

    for (auto start = std::chrono::steady_clock::now(), now = start; now < start + std::chrono::seconds{60}; now = std::chrono::steady_clock::now()) 
    {}  
    

    【讨论】:

      【解决方案4】:

      您只需在循环中插入时间检查即可实现。 由于C++11,你可以使用chrono standard library

      这个想法是following code snippet中显示的那个。

      我在模板中设计了该函数,以便更通用并仅显示带有计时器的条件循环。

      即:

      template <std::int64_t Seconds, typename Fn, typename... Args>
      void repeat_for_seconds(Fn&& fn, Args&&... args) {
        using ClockType = std::chrono::system_clock;
      
        // Time at the start of the function
        auto time_start = ClockType::now();
      
        while (std::chrono::duration_cast<std::chrono::seconds>(ClockType::now() -
                                                                time_start)
                   .count() < Seconds) {
          /* execute code you want in the while loop */
        }
      }
      

      因为 ideone 策略 sn-p 有 3 秒的延迟,但您可以在第一个模板参数中轻松更改它。

      【讨论】:

        【解决方案5】:

        这是一个使用 chrono 的工作示例

        #include<iostream>
        #include <chrono>
        using namespace std;
        int main()
        {
            int a=1;
            int b;
            cout<<"3.";
            b=a*10%7;
        
            auto start = std::chrono::system_clock::now();
            auto end = std::chrono::system_clock::now();
            while((std::chrono::duration_cast<std::chrono::seconds>(end - start).count() != 60))
        
            {
                end = std::chrono::system_clock::now();
                cout<<"Time is"<<std::chrono::duration_cast<std::chrono::seconds>(end - start).count()<<" second"<<endl;
        
                cout<<a/7<<endl;
                a=b*10;
                b=a%7;
            }
        }
        

        输出(部分输出)

        4
        Time is59 second
        2
        Time is60 second
        8
        Program ended with exit code: 0
        

        【讨论】:

          【解决方案6】:

          您可以使用 time.h 确保循环不会在 60 秒后执行后续时间!

          #include <time.h>
          using namespace std;
          
          clock_t start = clock();
          while ( (clock() - start)/CLOCKS_PER_SEC <= 60)
              //do stuff here
          

          这实质上是获取当前时间的时钟数并将其分配给start。之后,循环的每次迭代,它都会检查当前时钟与start 时钟之间的差异,除以每秒时钟因子进行转换,是否小于或等于您想要的 60 秒。

          【讨论】:

          • CLOCKS_PER_SECOND 在哪里定义?请。
          • @GaryCarlyleCook 不要上当。它被称为 time.h 中定义的 CLOCKS_PER_SEC
          【解决方案7】:

          一种方法是注册一个信号处理程序 60 秒。

          以下是使用信号处理程序的示例程序:

          #include <stdio.h>
          #include <stdlib.h>
          #include <stdbool.h>
          #include <sys/time.h>
          #include <signal.h>
          #include <unistd.h>
          
          #define INTERVAL 60             // number of seconds to go off
          
          void sigTimerStop(int signum) {
              printf("Timer ran out! Stopping timer\n");
          }
          
          void sigTimerSet(int interval) {
              printf("starting timer\n");
              struct itimerval it_val;
          
              it_val.it_value.tv_sec = interval;
              it_val.it_value.tv_usec = 0;
              it_val.it_interval.tv_sec = 0;
              it_val.it_interval.tv_usec = 0;
          
              if (signal(SIGALRM, sigTimerStop) == SIG_ERR) {
                  perror("Unable to catch SIGALRM");
                  exit(1);
              }
              if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
                  perror("error calling sigsetitimer()");
                  exit(1);
              }
          }
          
          int main(int argc, char *argv[]) {
          
              sigTimerSet(INTERVAL);
          
              while (1) {
                  // do stuff
              }
              return 0;
          }
          

          【讨论】:

            猜你喜欢
            • 2013-12-24
            • 1970-01-01
            • 1970-01-01
            • 2020-09-19
            • 1970-01-01
            • 1970-01-01
            • 2017-06-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多